< script type =" text / javascript" src =" json.js">< / script> < script type =" text / javascript"> var jsonStr1 =''{" one":[1,3]}''; var jsonStr2 =''{" one":[2],'' +''" two":[1]}''; 函数jsonAdd(str1,str2){ var obj1 = eval(' '(''+ str1 +'')''); var obj2 = eval(''(''+ str2 +'')''); for(var prop in obj2){ if(obj2 [prop] instanceof Array){ if(prop in obj1){ obj1 [prop] = obj1 [prop] .concat(obj2 [prop]); } else { obj1 [prop] = obj2 [prop] .concat(); } } } 返回obj1.toJSONString(); } alert(jsonAdd(jsonStr1,jsonStr2)); < / script> 其中json.js可以在:< URL: http://www.json.org/json.js >。如果 你不想扩展Array原型(因此可以 删除instanceof Array测试),有一个功能化的版本 $ b json.org已不再提供$ b - 已在此处发布: < URL: http://groups.google.com。 au / group / ru ... 43fb9e0b2f5a3d - Rob Is there a function or library somewhere that merges 2 JSON datastructures? For instance this: { "one": [1,3] } plus { "one": [2] } equals { "one": [1,2,3] } 解决方案 This is a very special case. In prototype library you findObject.extend(), but it overwrites same keys. You need a specialfuncion that concats Arrays key for key (if the key holds an array),e.g. Object.plus = function(obj1, obj2) {var res = {};// "copy" obj1 keys to new object resObject.extend(res, obj1);// now overwrite obj1 keys in res by contents of obj2Object.extend(res, obj2);// now consider overwritten obj 1 keys one by one, like in example -only arraysfor(var key in obj1) {if (obj1[key] instanceof Array)// concatenate Arrays, don''t sort them like in your exampleres[key] = obj1[key].concat(res[key]);}} I hope I could help you, for Object.extend look in http://script.aculo.us/prototype.js Andi If you are specifically after the above structure, then the followingshould do the trick: <script type="text/javascript" src="json.js"></script><script type="text/javascript"> var jsonStr1 = ''{ "one": [1,3] }'';var jsonStr2 = ''{ "one": [2],''+ '' "two": [1]}''; function jsonAdd(str1, str2){var obj1 = eval(''('' + str1 + '')'');var obj2 = eval(''('' + str2 + '')'');for (var prop in obj2){if (obj2[prop] instanceof Array){if (prop in obj1){obj1[prop] = obj1[prop].concat(obj2[prop]);} else {obj1[prop] = obj2[prop].concat();}}}return obj1.toJSONString();} alert( jsonAdd(jsonStr1, jsonStr2) ); </script> where json.js can be found at: <URL: http://www.json.org/json.js >. Ifyou don''t want to extend the Array prototype (and therefore couldremove the instanceof Array test), there is a functionalised versionthat is no longer available from json.org - it has been posted here:<URL: http://groups.google.com.au/group/ru...43fb9e0b2f5a3d --Rob 这篇关于合并JSON结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-21 03:30