简体   繁体   中英

How to combine two JSON strings for storage in database

I have the following data that really should be one JSON string however I am not sure to combine the two into a valid JSON string. I think lack of sleep is making me not think properly.

{"0":{"a":"22","b":"44","b":"77"}} {"1":{"a":"2200","b":"4400","c":"7700"}}

I really want it to be something like:

{"0":{"a":"22","b":"44","b":"77"}, "1":{"a":"2200","b":"4400","c":"7700"}} (i am assuming this is a valid JSON string

  1. Convert both strings to objects
  2. Use for (var foo in bar) to loop over all the properties of one object, and copy to the other object
  3. Convert back to a string

http://jsfiddle.net/4S2wC/应该是您正在寻找的,如果我正确理解您的问题

You could try a regex such as:

mystring.replace(/}}\s*{/g,"},");

This makes some assumptions around the depth of the object graph and the syntax.

Below function is helps to combine the json object.

C#:
        public String toJSONCombine(JSONObject outer, int HVal, int Aval , int Bval , int Cval)
        {    
             JSONObject inner = new JSONObject();
             try {
              inner.put("a", Aval);
              inner.put("b", Bval);
              inner.put("C", Cval);
              outer.put(HVal, inner);
             } 
             catch (JSONException ex) {
               ex.printStackTrace();
             }
        }

You can form the json string like that at end

{"0":{"a":"22","b":"44","b":"77"}, "1":{"a":"2200","b":"4400","c":"7700"}}

I think you want to js. We can make it same Structure using javascripts..

Using array instead of JsonObject..

I hope its help to you

Why people create their own function always, it's really out of my mind. There are lot's of functions out there for you, why not use those? Jquery has some really good functions about these, like

$.extend({},j1,j2) http://api.jquery.com/jQuery.extend/

$.merge( [0,1,2], [2,3,4] ) for array marge http://api.jquery.com/jQuery.merge/

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM