Skip to content
Esc
  • MQTT Topic MatcherTest MQTT topic filters with + and # wildcards against topics, and check ACL patterns.
  • JSON FormatterBeautify, minify and validate JSON instantly as you type.
  • JSON DiffCompare two JSON documents and see every added, removed and changed value by path.
  • JSON to TypeScriptGenerate TypeScript interfaces or Zod schemas from a sample JSON response.
  • Base64 Encoder/DecoderConvert text to Base64 and back, with full Unicode support.
  • UUID GeneratorGenerate random v4 UUIDs — one or many — in the format you need.
  • JWT DecoderDecode JSON Web Tokens to inspect the header, payload and expiry.
  • Timestamp ConverterConvert Unix timestamps to dates and dates to timestamps.
  • URL Encoder/DecoderPercent-encode and decode URLs, and break down query strings.
  • Hash GeneratorGenerate MD5, SHA-1, SHA-256 and SHA-512 hashes of text or files.
  • Regex TesterTest regular expressions with live match highlighting and groups.
  • YAML to JSON ConverterConvert YAML to JSON and JSON to YAML, with clear error locations.
  • SQL FormatterBeautify or minify SQL for PostgreSQL, MySQL, SQL Server and 9 more dialects.
  • Mock Data GeneratorGenerate realistic fake data for API mocks as JSON, CSV or SQL inserts.
  • HTTP Header AnalyzerGrade response headers: CSP, HSTS, cookies, CORS and caching, explained.
  • Webhook Signature VerifierVerify and generate webhook signatures for GitHub, Stripe, Slack, Shopify and more.
  • Cron Expression GeneratorBuild and explain cron schedules, with the next run times in any time zone.
  • .env File ValidatorFind syntax errors, duplicates and missing keys in .env files.
  • HTML to JSX ConverterConvert HTML to valid React JSX: className, style objects, self-closing tags.
  • SVG to React ComponentTurn SVG files into React icon components with props and currentColor.
  • Markdown EditorWrite Markdown with a live preview, GitHub tables and task lists, and HTML export.

↑ ↓ to moveEnter to openPaste data to open it in the right tool. Nothing leaves your browser.

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 }); // false

The 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:

  1. Does key order matter? Almost never — JSON objects are unordered.
  2. Does array order matter? Usually yes (a list of steps), sometimes no (a set of tags or roles).
  3. Is null the same as a missing key? In JSON they're different, but your API might treat them the same.
  4. Are "42" and 42 the 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 counts

In 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 }, {});                                       // false

Arrays 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: true

Step 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 counts

If 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.parse turns numbers into 64-bit floats, so 9007199254740993 becomes 9007199254740992 and two different IDs can compare as equal. APIs should send such IDs as strings.
  • Comparing floating-point results exactly. 0.1 + 0.2 === 0.3 is false; compare computed numbers with a tolerance such as Math.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; compare Date.parse results when that matters.
  • Forgetting that JSON.stringify drops undefined. { 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.