Reputation: 89
In some questions here in stackoverflow show how to merge two JSON objects from inner HTML or in a var but I want to merge two external JSON files or URLs with JSON response.
Here an exemple with local vars: http://jsfiddle.net/qhoc/agp54/
var object1 = {name: "John"};
var object2 = {location: "San Jose"};
var objectA = $.extend({}, object1, object2);
//var objectB = object1.concat(object2);
console.log(objectA);
Then I will get my JSON like this or similar:
jQuery.getJson("data.json", function(data){...};
Any hint for concat my two JSONs: json1.json
and json2.json
? :)
Upvotes: 2
Views: 6173
Reputation: 86064
You're almost there. You just need to re-serialize after you do the extend.
var a = '{"foo": 1}';
var b = '{"bar": 2}';
var combined = $.extend({},
JSON.parse(a),
JSON.parse(b));
var serialized = JSON.stringify(combined);
Upvotes: 4
Reputation: 639
With jQuery you can merge two objects with
jQuery.getJson("data.json", function(data) {
jQuery.getJson("data2.json", function(data2) {
var concatenatedJson = $.extend({}, data, data2);
});
});
So that you can of course only do, after both json objects are loaded.
Upvotes: 0