开发者

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


http://jsfiddle.net/4S2wC/ should be what you're looking for, if I understand your question correctly


  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


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/

How to combine two JSON strings for storage in database

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜