Comparing JSON Documents: Diff Tools and Techniques

jsondiffcomparisontesting

Comparing JSON documents is essential for debugging APIs, testing, version control, and configuration management.

Why Compare JSON?

  • API Testing — Verify responses match expected output
  • Config Changes — Track what changed between deployments
  • Data Sync — Detect differences between local and remote data
  • Debugging — Find what changed that caused a bug
  • 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:

  • deep-diff — Detailed diff with path information
  • jsondiffpatch — Rich diff with visual output
  • fast-json-patch — RFC 6902 JSON Patch format
  • 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.

    Related Tools