Comparing JSON documents is essential for debugging APIs, testing, version control, and configuration management.
Why Compare JSON?
Simple Equality Check
// Quick and dirty
JSON.stringify(obj1) === JSON.stringify(obj2)
// Better: sorted keys
JSON.stringify(obj1, Object.keys(obj1).sort()) ===
JSON.stringify(obj2, Object.keys(obj2).sort())
This only tells you IF they differ, not WHAT differs.
Deep Diff Function
function deepDiff(obj1, obj2) {
const diff = {};
const allKeys = new Set([
...Object.keys(obj1),
...Object.keys(obj2)
]);
for (const key of allKeys) {
if (!(key in obj1)) {
diff[key] = { added: obj2[key] };
} else if (!(key in obj2)) {
diff[key] = { removed: obj1[key] };
} else if (JSON.stringify(obj1[key]) !== JSON.stringify(obj2[key])) {
if (typeof obj1[key] === 'object' && typeof obj2[key] === 'object') {
diff[key] = deepDiff(obj1[key], obj2[key]);
} else {
diff[key] = { from: obj1[key], to: obj2[key] };
}
}
}
return diff;
}
Using Diff Libraries
For production use, consider these libraries:
JSON Patch (RFC 6902)
Standard patch operations:
[
{ "op": "replace", "path": "/name", "value": "New Name" },
{ "op": "add", "path": "/email", "value": "test@example.com" },
{ "op": "remove", "path": "/temp" }
]
JSON Merge Patch (RFC 7396)
Simpler format for partial updates:
{
"name": "Updated Name",
"temp": null
}
Use our JSON Validator to ensure your diff outputs are valid JSON.