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: /
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
? :)
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/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
? :)
{a:"one"}
and {a:"two"}
, for instance? If "a" is "latest published", then maybe you want to keep only the second value. If it's not, maybe you need the first? Or an array of both values? You can't "merge" unless you know the data's model, so that'd be task 1: find out what the JSON's model is, and validate it against that so your notion of what merging means applies.
– Mike 'Pomax' Kamermans
Commented
Nov 13, 2014 at 17:14
$.getJSON
, and you already know how to merge them once you get them using $.extend()
, so I don't see what the problem is. Are you saying you want to convert it back to JSON when done?
– user1106925
Commented
Nov 13, 2014 at 18:22
You're almost there. You just need to re-serialize after you do the extend.
var a = '{"foo": 1}';
var b = '{"bar": 2}';
var bined = $.extend({},
JSON.parse(a),
JSON.parse(b));
var serialized = JSON.stringify(bined);
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.