If you're not utilizing jQuery, implement it in the following way:
function mergeJSON(json1, json2) {
var combined_JSON = {};
// Deep copy of json1 object literal
for (var key in json1) {
combined_JSON[key] = json1[key];
}
// Copy other values from json2
for (var key in json2) {
if (!json1.hasOwnProperty(key))
combined_JSON[key] = json2[key];
}
return combined_JSON;
}
var json1 = {val1: 1, val2: 2, val3: 3};
var json2 = {val1: 52, val2: 56, val7: 7, val5: 5, val3: 33};
var merged_json = mergeJSON(json1, json2);
If you are using jQuery, the process is simpler
var json1 = {val1: 1, val2: 2, val3: 3};
var json2 = {val1: 52, val2: 56, val7: 7, val5: 5, val3: 33};
var merged_json = $.extend({}, json2, json1);
EDIT
Following the updated question, here is an updated solution to handle nested literals scenario
For your information, in the next solution I will assume that you are not using jQuery since it wasn't mentioned in your question
function mergeNestedJSON(json1, json2) {
// private function to recursively traverse json objects
function traverse(object, callback) {
for (var key in object) {
// only return leaf nodes
if ((/boolean|number|string/).test(typeof object[key]))
callback.apply(this, [object, key, object[key]);
// if not base condition, dig deeper into recursion
if (object[key] !== null && typeof(object[key]) == "object")
traverse(object[key], callback);
}
}
// create a deep clone copy of json1
var result = JSON.parse(JSON.stringify(json1));
// create a flattened version of json2 for optimized lookups
var flat_json2 = {};
traverse(json2, function(object, key,value) {
flat_json2[key] = value;
});
// overwrite values in results if they exist in json2
traverse(result, function(object, key, value) {
if (typeof flat_json2[key] !== "undefined")
object[key] = flat_json2[key];
});
return result;
}
// Now, let's test it
var json1 = {wrapper: {val1: 1, val2: 2}}
var json2 = {val1: 'without wrapper'}
var merged_json = mergeNestedJSON(json1, json2);
// check the result with a simple alert
alert(JSON.stringify(merged_json));
Here is a JSFiddle Sample click here