Two API responses, two config files, an expected and an actual fixture: comparing JSON comes up constantly in tests, migrations and debugging. The quick approach, comparing JSON.stringify output, works until a key moves. This article covers correct equality checks, a diff that tells you what changed, and command-line options for files.
Why JSON.stringify comparison fails
const a = { id: 1, name: "Ada" };
const b = { name: "Ada", id: 1 };
JSON.stringify(a) === JSON.stringify(b); // false
The data is identical, but JSON.stringify writes keys in insertion order, so the strings differ. JSON objects are unordered by definition, so any comparison should ignore key order while still respecting array order.
Option 1: compare with sorted keys
The smallest fix is to sort keys recursively before stringifying:
function canonical(value) {
if (Array.isArray(value)) return value.map(canonical);
if (value && typeof value === "object") {
return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])]));
}
return value;
}
const sameJson = (a, b) => JSON.stringify(canonical(a)) === JSON.stringify(canonical(b));
sameJson(a, b); // true
This is fine for small values and tests. It builds full strings, so for large documents a direct recursive comparison is faster.
Option 2: a deep equality function for JSON values
JSON has only six kinds of values (object, array, string, number, boolean, null), so a complete comparison is short:
function jsonEqual(a, b) {
if (a === b) return true;
if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
if (Array.isArray(a) !== Array.isArray(b)) return false;
if (Array.isArray(a)) return a.length === b.length && a.every((item, i) => jsonEqual(item, b[i]));
const keys = Object.keys(a);
return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && jsonEqual(a[key], b[key]));
}
It deliberately ignores things JSON can't contain, such as Date objects, Maps and class instances. For general JavaScript values, use a library: Lodash's _.isEqual, or node:assert's deepStrictEqual in tests, which also prints a readable diff when it fails:
import assert from "node:assert/strict";
assert.deepEqual(actual, expected);
Option 3: list exactly what changed
A boolean says "different" but not where. A diff function walks both values and records each difference with its path:
function diff(before, after, path = "$", changes = []) {
if (jsonEqual(before, after)) return changes;
const bothObjects = before && after && typeof before === "object" && typeof after === "object"
&& Array.isArray(before) === Array.isArray(after);
if (!bothObjects) {
changes.push({ path, type: "changed", before, after });
return changes;
}
const keys = new Set([...Object.keys(before), ...Object.keys(after)]);
for (const key of keys) {
const child = Array.isArray(before) ? `${path}[${key}]` : `${path}.${key}`;
if (!(key in after)) changes.push({ path: child, type: "removed", before: before[key] });
else if (!(key in before)) changes.push({ path: child, type: "added", after: after[key] });
else diff(before[key], after[key], child, changes);
}
return changes;
}
diff({ version: "1.2.0", tags: ["a"] }, { version: "1.3.0", tags: ["a", "b"], beta: true });
// [
// { path: "$.version", type: "changed", before: "1.2.0", after: "1.3.0" },
// { path: "$.tags[1]", type: "added", after: "b" },
// { path: "$.beta", type: "added", after: true }
// ]
This compares arrays by position, which has one weakness: inserting an item at the start reports every later item as changed. Tools that handle this well match array items with an algorithm such as longest common subsequence before comparing them. The JSON Diff checker does that, so inserting one item shows up as one addition.
If you need to apply the differences elsewhere, express them as JSON Patch operations instead of a custom format; libraries such as fast-json-patch generate and apply them.
Compare JSON files from the command line
With jq
jq -S sorts keys, which normalizes both files so a plain diff shows only real changes:
diff <(jq -S . before.json) <(jq -S . after.json)
To get a simple yes or no, compare inside jq:
jq -n --slurpfile a before.json --slurpfile b after.json '$a == $b'
With Python
Python dictionaries compare by content, regardless of key order:
import json
with open("before.json") as f1, open("after.json") as f2:
print(json.load(f1) == json.load(f2))
In Git
git diff compares text, so a reformatted file looks completely changed. Normalize formatting before committing (a pretty printer with sorted keys), and diffs stay readable.
Pitfalls
- Numbers:
1,1.0and1e0are the same number after parsing, but different text. Compare parsed values, not strings. - Large integers: above 2^53, JavaScript parses different integers to the same number, so a diff can miss a change in a 19-digit ID.
- Volatile fields: timestamps and request IDs differ on every response. Remove them before comparing, for example with a replacer or
jq 'del(.meta.requestId)'. - Types: the number
1and the string"1"are different values. A good diff reports that as a change.