{ }JSON Compare

Guide · jq, Python, Node.js

Compare Two JSON Files

The exact commands for jq, Python and Node.js, including how to ignore key order and what each approach misses.

The one command that solves most cases

If both files are valid JSON and you just want to know what changed, sort the keys on both sides and diff the text:

jq --sort-keys . before.json > /tmp/before.json
jq --sort-keys . after.json > /tmp/after.json
diff -u /tmp/before.json /tmp/after.json

--sort-keys (short form -S) rewrites every object with its keys in alphabetical order, at every level of nesting. diff -u then produces the familiar unified output: - for lines only in the first file, + for lines only in the second. The exit status is 0 when the files match and 1 when they differ, which is exactly what a CI step needs.

Why sorting keys first is not optional

Run a plain diff on two JSON files produced by different systems and you will often get a wall of changes that says nothing. The two documents hold the same data, but one serializer wrote id first and the other wrote name first. JSON objects are unordered by definition, so neither file is wrong, and the diff is answering a question nobody asked.

Sorting keys first removes that whole class of noise. It also makes the output stable: the same pair of documents always produces the same diff, which matters when the diff goes into a review or a changelog.

Two things --sort-keys does not do. It does not sort arrays: array order is meaningful in JSON, and jq leaves it alone. And it does not normalize number formatting: 1.0 stays 1.0.

Python with DeepDiff

When you need the differences as data — to assert on them, count them, or write them to a report — use a library instead of text diffing.

pip install deepdiff
import json
from deepdiff import DeepDiff

with open("before.json") as f:
    before = json.load(f)
with open("after.json") as f:
    after = json.load(f)

diff = DeepDiff(before, after, ignore_order=True)
print(diff.pretty())

ignore_order=True makes lists compare as unordered collections as well as ignoring object key order, which is usually what you want for API responses whose items come back in an arbitrary order. Be aware of the trade-off: if a genuine reordering in a list is a change you care about, leave it off. DeepDiff returns an empty result object when the two documents are equal, so if not diff: is a valid assertion.

Python without a dependency

If you cannot add a package, this recursive walk covers the four cases that matter: added keys, removed keys, changed values, changed types.

def walk(a, b, path="$"):
    if type(a) is not type(b):
        yield f"{path}: type {type(a).__name__} -> {type(b).__name__}"
        return
    if isinstance(a, dict):
        for k in a.keys() | b.keys():
            p = f"{path}.{k}"
            if k not in b:
                yield f"{p}: removed"
            elif k not in a:
                yield f"{p}: added"
            else:
                yield from walk(a[k], b[k], p)
    elif isinstance(a, list):
        for i in range(max(len(a), len(b))):
            p = f"{path}[{i}]"
            if i >= len(b):
                yield f"{p}: removed"
            elif i >= len(a):
                yield f"{p}: added"
            else:
                yield from walk(a[i], b[i], p)
    elif a != b:
        yield f"{path}: {a!r} -> {b!r}"

for line in walk(before, after):
    print(line)

Python dictionaries keep insertion order, so keys are compared by name here and never by position — the same behaviour as the ignore-key-order switch in the browser tool.

Node.js

Two ways, depending on whether you want output or an assertion.

npx json-diff before.json after.json

The json-diff package prints a coloured, key-by-key comparison and exits non-zero when the documents differ, which makes it usable as a test command. Object keys are compared by name, not by insertion order.

For a plain assertion with no dependency, Node's deep equality is enough:

import assert from "node:assert/strict";
import { readFileSync } from "node:fs";

const before = JSON.parse(readFileSync("before.json", "utf8"));
const after = JSON.parse(readFileSync("after.json", "utf8"));

assert.deepStrictEqual(before, after);

deepStrictEqual compares object keys regardless of order and also checks types, so 1 and "1" fail. What it does not do is tell you where the difference is in a friendly way — the assertion message is readable but terse. When you need the actual list of differences, use the json-diff command above or a browser comparison.

In CI

A GitHub Actions step that fails the build when a config snapshot drifts:

- name: Compare JSON snapshots
  run: |
    jq --sort-keys . expected.json > /tmp/expected.json
    jq --sort-keys . actual.json > /tmp/actual.json
    diff -u /tmp/expected.json /tmp/actual.json

Keep the sorted files around as artifacts when the step fails. Reading a diff from the raw log is much worse than downloading two small JSON files.

When to skip the script

Scripts are the right answer for anything repeatable. They are the wrong answer for a one-off look at two documents you have in front of you, and they are a bad answer for payloads you should not send anywhere: a production config, a customer record, an auth token in a response. For those, use a comparison that runs locally in the browser — JSON Compare does not upload anything, and it lists each changed path with its old and new value instead of making you read pairs of diff lines.

Frequently asked questions

What is the fastest way to compare two JSON files in a terminal?

`jq --sort-keys . a.json > a.json` and the same for the second file, then `diff -u a.json b.json`. Sorting keys at every level removes the noise caused by serializers writing keys in different orders.

Does jq --sort-keys also sort arrays?

`--sort-keys` (or `-S`) only sorts object keys. Arrays keep their order, because array order is part of the data. If your arrays should be order-insensitive, sort them explicitly first with something like `jq 'walk(if type == "array" then sort_by(tojson) else . end)'`.

Can Python compare JSON while ignoring key order?

Yes. `json.dumps(obj, sort_keys=True)` canonicalizes the keys, and `DeepDiff` compares object keys by name regardless of order. Python dictionaries preserve insertion order, which is why an unordered comparison has to be explicit rather than assumed.

How do I diff two JSON files in Node.js?

`npx json-diff before.json after.json` prints a key-by-key comparison and exits non-zero when they differ. For a pure assertion, `assert.deepStrictEqual` from `node:assert/strict` compares both structure and types.

Should I use a script or a browser tool?

The commands above run on your machine or in the runner. A browser comparison runs in the tab and uploads nothing, which matters for production configs and customer payloads. Use the script for anything repeatable, the browser for one-off inspection.

Why does adding one array element look like a huge change?

Arrays are compared by position in every recipe above. Inserting one element shifts every later index, so the diff reports all of them. That is correct for JSON array order, but it is noise if your API returns unordered lists.