Deep Equality Check for JSON Documents

Learn how JSON diff tools perform deep equality checks to determine if two documents are semantically identical despite differences in formatting, key order, or whitespace.

Type & Value Edge Cases

Detailed Explanation

Deep equality means two JSON documents represent the exact same data structure with the exact same values at every level of nesting. A deep equality check is the foundation of JSON diffing: if two documents are deeply equal, the diff is empty.

What deep equality ignores:

  1. Key order: {"a":1,"b":2} and {"b":2,"a":1} are deeply equal because JSON objects are unordered.
  2. Whitespace and formatting: Minified and pretty-printed versions of the same data are deeply equal.
  3. Trailing commas / comments: These are not valid JSON, but if a parser strips them before comparison, the resulting structures may be deeply equal.

What deep equality checks:

  1. Types must match: "42" (string) and 42 (number) are NOT deeply equal.
  2. Values must match exactly: 3.14 and 3.140 are deeply equal (same IEEE 754 value), but 3.14 and 3.14159 are not.
  3. Array order matters: [1, 2, 3] and [3, 2, 1] are NOT deeply equal because arrays are ordered.
  4. Null vs. absent: { "a": null } and {} are NOT deeply equal.
// Document A
{
  "users": [
    { "id": 1, "name": "Alice" },
    { "id": 2, "name": "Bob" }
  ],
  "count": 2
}

// Document B
{
  "count": 2,
  "users": [
    { "id": 1, "name": "Alice" },
    { "id": 2, "name": "Bob" }
  ]
}

These two documents are deeply equal despite different key order at the root level. The array contents are in the same order, so they are also equal.

Implementation in JavaScript:

JavaScript's === operator compares object references, not values, so {a:1} === {a:1} is false. Deep equality requires a recursive comparison function. Libraries like Lodash (_.isEqual) or custom implementations are commonly used. The JSON.stringify() trick (stringifying both and comparing strings) works only if key order is guaranteed to be the same.

Performance:

Deep equality checking is O(n) where n is the total number of nodes in the document. For documents with millions of keys, consider hashing subtrees for quick inequality detection before performing full comparison.

Use Case

Writing automated tests that verify an API response matches an expected JSON fixture, where key order may vary between test runs but the data must be structurally identical.

Try It — JSON Diff

Open full tool