jsondecode.com logo

HomeChevronBlogChevronHow to Compare Two JSON Objects: Diff, Merge, and Validate

Blog post

How to Compare Two JSON Objects: Diff, Merge, and Validate

Learn how to compare two JSON objects in JavaScript and Python — deep equality checks, structural diff, finding added/removed/changed keys, and merge strategies.

author

Shashank Jain

Author

22/05/20261 minute 14 seconds read
How to Compare Two JSON Objects: Diff, Merge, and ValidateHow to Compare Two JSON Objects: Diff, Merge, and Validate

Article

Why Compare JSON Objects?

Comparing JSON is essential for API testing (did the response change?), config management (what changed between deploys?), and data pipelines (detect schema drift).

Deep Equality in JavaScript

// JSON.stringify comparison (works for simple cases)
JSON.stringify(obj1) === JSON.stringify(obj2)
// Warning: key order matters! {a:1,b:2} !== {b:2,a:1}

// Better: sort keys first
const normalize = (obj) => JSON.stringify(obj, Object.keys(obj).sort());
normalize(obj1) === normalize(obj2);

Deep Equality in Python

# Python dict comparison is deep by default
obj1 = {"name": "Alice", "age": 30}
obj2 = {"name": "Alice", "age": 30}
print(obj1 == obj2)  # True

# For complex nested structures
import json
json.dumps(obj1, sort_keys=True) == json.dumps(obj2, sort_keys=True)

Finding What Changed: Structural Diff

function jsonDiff(a, b, path = "") {
  const changes = [];
  const allKeys = new Set([...Object.keys(a), ...Object.keys(b)]);
  for (const key of allKeys) {
    const fullPath = path ?  : key;
    if (!(key in a)) changes.push({ type: "added", path: fullPath, value: b[key] });
    else if (!(key in b)) changes.push({ type: "removed", path: fullPath, value: a[key] });
    else if (typeof a[key] === "object" && a[key] !== null) {
      changes.push(...jsonDiff(a[key], b[key], fullPath));
    } else if (a[key] !== b[key]) {
      changes.push({ type: "changed", path: fullPath, from: a[key], to: b[key] });
    }
  }
  return changes;
}

Online JSON Diff Tool

For a quick visual diff, use the JSON Diff tool at jsondecode.com — paste two JSON objects and see added, removed, and changed keys highlighted instantly.

Merging JSON Objects

// Shallow merge (Object.assign)
const merged = Object.assign({}, defaults, overrides);

// Deep merge
function deepMerge(target, source) {
  const result = { ...target };
  for (const key of Object.keys(source)) {
    if (typeof source[key] === "object" && !Array.isArray(source[key])) {
      result[key] = deepMerge(target[key] || {}, source[key]);
    } else {
      result[key] = source[key];
    }
  }
  return result;
}

Keep reading

Recent blogs

View all

If jsondecode.com saved you time, share it with your team

Free forever. No ads. No sign-up. Help other developers find it.