Guide
How to compare two JSON objects
You have two API responses, two config files or an expected and an actual test result, and you need to know whether they're the same — and if not, exactly what changed.
Updated · 4 min read
The problem
The obvious approaches give wrong answers. === compares object identity, not contents, and comparing JSON.stringify output depends on the order the keys were written in — which JSON says doesn't matter.
const a = { id: 1, tags: ["x"] };
const b = { id: 1, tags: ["x"] };
a === b; // false — two different objects
JSON.stringify(a) === JSON.stringify(b); // true, but only by luck:
JSON.stringify({ a: 1, b: 2 }) === JSON.stringify({ b: 2, a: 1 }); // falseThe last two objects hold exactly the same data, but the strings differ because the keys are in a different order. A server that builds its response from a hash map can return keys in any order, so string comparison produces false alarms.
Step 1: Decide what “equal” means
Before writing code, answer four questions. Each one changes the result:
- Does key order matter? Almost never — JSON objects are unordered.
- Does array order matter? Usually yes (a list of steps), sometimes no (a set of tags or roles).
- Is
nullthe same as a missing key? In JSON they're different, but your API might treat them the same. - Are
"42"and42the same? Not in JSON — one is a string and one is a number — but a loosely typed backend might send either.
Step 2: Check whether they're equal
In Node.js, util.isDeepStrictEqual compares structure and ignores key order:
import { isDeepStrictEqual } from "node:util";
isDeepStrictEqual({ a: 1, b: 2 }, { b: 2, a: 1 }); // true
isDeepStrictEqual([1, 2], [2, 1]); // false — array order countsIn the browser there's no built-in equivalent. For parsed JSON — which can only contain objects, arrays, strings, numbers, booleans and null — a short recursive function is enough:
function deepEqual(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;
const keysA = Object.keys(a);
const keysB = Object.keys(b);
if (keysA.length !== keysB.length) return false;
return keysA.every((key) => Object.hasOwn(b, key) && deepEqual(a[key], b[key]));
}
deepEqual({ a: 1, b: [1, { c: 2 }] }, { b: [1, { c: 2 }], a: 1 }); // true
deepEqual({ a: null }, {}); // falseArrays work too: Object.keys returns their indexes, so arrays of different lengths fail the length check and items are compared position by position.
Step 3: List what changed
A yes/no answer isn't much help when a test fails. Walking both values together and recording a path for each difference tells you exactly where to look:
function diff(a, b, path = "$") {
if (a === b) return [];
const bothObjects = typeof a === "object" && typeof b === "object" && a !== null && b !== null &&
Array.isArray(a) === Array.isArray(b);
if (!bothObjects) return [`~ ${path}: ${JSON.stringify(a)} → ${JSON.stringify(b)}`];
const changes = [];
for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) {
const child = Array.isArray(a) ? `${path}[${key}]` : `${path}.${key}`;
if (!Object.hasOwn(b, key)) changes.push(`- ${child}: ${JSON.stringify(a[key])}`);
else if (!Object.hasOwn(a, key)) changes.push(`+ ${child}: ${JSON.stringify(b[key])}`);
else changes.push(...diff(a[key], b[key], child));
}
return changes;
}const before = { id: 1042, email: "ada@example.com", roles: ["admin", "dev"], plan: { tier: "pro" } };
const after = { id: 1042, email: "ada@company.com", roles: ["admin"], plan: { tier: "team" }, active: true };
console.log(diff(before, after).join("\n"));
// ~ $.email: "ada@example.com" → "ada@company.com"
// - $.roles[1]: "dev"
// ~ $.plan.tier: "pro" → "team"
// + $.active: trueStep 4: Ignore array order when it doesn't matter
For arrays that are really sets — tags, roles, permissions — compare the items regardless of position. Serialising each item and sorting the results works for any JSON values and keeps duplicates:
const sameItems = (x, y) => {
const key = (v) => JSON.stringify(v);
return x.length === y.length && x.map(key).sort().join() === y.map(key).sort().join();
};
sameItems(["read", "deploy"], ["deploy", "read"]); // true
sameItems([1, 1, 2], [1, 2, 2]); // false — different countsIf the items are objects, JSON.stringify is sensitive to their key order again. Sort keys first, or match items by an ID field instead.
Common mistakes
- Comparing raw response text. A minified and a pretty-printed copy of the same data never match as strings — parse both first.
- Trusting large integer IDs.
JSON.parseturns numbers into 64-bit floats, so9007199254740993becomes9007199254740992and two different IDs can compare as equal. APIs should send such IDs as strings. - Comparing floating-point results exactly.
0.1 + 0.2 === 0.3isfalse; compare computed numbers with a tolerance such asMath.abs(x - y) < 1e-9. - Comparing timestamps as strings.
"2026-11-27T09:30:00Z"and"2026-11-27T09:30:00.000Z"are the same instant but different strings; compareDate.parseresults when that matters. - Forgetting that
JSON.stringifydropsundefined.{ a: undefined, b: 1 }serialises as{"b":1}, so objects built in JavaScript can look equal after a round trip when they weren't before. - Expecting fields that change on every request (request IDs,
updatedAt) to match. Remove them from both sides before comparing in a test.
Compare JSON without writing code
The JSON Diff tool does all of the above in your browser: it parses both documents, ignores key order, lists every change by path, can ignore array order, and turns the result into a JSON Patch. Use the JSON Formatter first if one side is minified or might be invalid.
Try the free JSON Diff
Compare two JSON documents and see every added, removed and changed value by path. Runs in your browser — nothing is uploaded.