function compareJsonStrings(jsonString1, jsonString2) {
let obj1 = JSON.parse(jsonString1);
let obj2 = JSON.parse(jsonString2);
function compareObjects(obj1, obj2, path = '') {
let diff = {};
// Compare keys in obj1
for (let key in obj1) {
if (!(key in obj2)) {
diff[path + key] = [obj1[key], undefined];
continue;
}
// Compare values
if (Array.isArray(obj1[key]) && Array.isArray(obj2[key])) {
let arrayDiff = compareArrays(obj1[key], obj2[key], path + key + '.');
if (Object.keys(arrayDiff).length > 0) {
diff[path + key] = arrayDiff;
}
} else if (typeof obj1[key] === 'object' && typeof obj2[key] === 'object') {
let childDiff = compareObjects(obj1[key], obj2[key], path + key + '.');
if (Object.keys(childDiff).length > 0) {
diff[path + key] = childDiff;
}
} else if (obj1[key] !== obj2[key]) {
diff[path + key] = [obj1[key], obj2[key]];
}
}
// Compare keys in obj2
for (let key in obj2) {
if (!(key in obj1)) {
diff[path + key] = [undefined, obj2[key]];
}
}
return diff;
}
function compareArrays(arr1, arr2, path = '') {
let diff = {};
// Compare elements in arr1
for (let i = 0; i < arr1.length; i++) {
if (i >= arr2.length) {
diff[path + i] = [arr1[i], undefined];
continue;
}
// Compare values
if (typeof arr1[i] === 'object' && typeof arr2[i] === 'object') {
let childDiff = compareObjects(arr1[i], arr2[i], path + i + '.');
if (Object.keys(childDiff).length > 0) {
diff[path + i] = childDiff;
}
} else if (arr1[i] !== arr2[i]) {
diff[path + i] = [arr1[i], arr2[i]];
}
}
// Compare elements in arr2
for (let i = arr1.length; i < arr2.length; i++) {
diff[path + i] = [undefined, arr2[i]];
}
return diff;
}
return compareObjects(obj1, obj2);
}
// Example usage:
let jsonString1 = '{"name": "John", "age": 30, "addresses": [{"street": "Main St", "city": "New York"}, {"street": "Oak St", "city": "Los Angeles"}]}';
let jsonString2 = '{"name": "Jane", "age": 30, "addresses": [{"street": "Main St", "city": "Los Angeles"}]}';
let diff = compareJsonStrings(jsonString1, jsonString2);
console.log(diff);
// Output: {name: ["John", "Jane"], addresses: {0: {city: ["New York", "Los Angeles"]}, 1: [Object]}}