Comparing two JSON files when the key order keeps changing
Two API responses that should be identical produce a diff with forty changed lines. Reading it, none of the values are different. The keys came back in a different order, one response is pretty printed and the other is not, and a text diff has no way to know any of that is irrelevant.
The fix is to normalise both documents before comparing them, so the diff shows only what actually changed.
Why key order moves around at all
JSON objects are unordered by definition. The specification describes an object as an unordered set of name and value pairs, so nothing requires a server to emit keys the same way twice.
In practice several things reorder them. A language with unordered maps, such as Go, will iterate in a deliberately randomised order. Serialising a database row produces whatever column order the query returned. Adding a field to a struct inserts it wherever the field was declared. A caching layer may reserialise through a different library than the origin.
None of this is a bug. It means a text diff is the wrong tool unless you prepare the input first.
Normalising before you compare
The goal is a canonical form: both documents sorted the same way, indented the same way, so the only remaining differences are real ones.
With jq:
jq -S . before.json > before.norm.json
jq -S . after.json > after.norm.json
diff before.norm.json after.norm.json
-S sorts object keys recursively, and . reformats with consistent indentation. Those two together remove almost all the noise.
With Python, if jq is not available:
python3 -c 'import json,sys; print(json.dumps(json.load(open(sys.argv[1])), sort_keys=True, indent=2))' before.json
If you would rather not shell out, the JSON formatter will reformat both documents consistently in the browser, and the diff checker compares the results side by side. Neither sends the input anywhere, which matters when the documents are real API responses with real customer data in them.
The part sorting does not fix: arrays
Sorting keys is safe because object key order carries no meaning. Array order does carry meaning, and that is where naive normalisation goes wrong.
[1, 2, 3] and [3, 2, 1] are genuinely different JSON values. A diff is right to flag them. But if the array is a list of records from a query with no ORDER BY, the order is accidental and you will get a large, useless diff every time the database feels like returning rows differently.
You have to decide, per array, whether order is meaningful. There is no general answer, which is why no tool can do this for you automatically.
When order is accidental and the elements have a stable identifier, sort by it before comparing:
jq -S '.users |= sort_by(.id)' before.json > before.norm.json
When elements are scalars and order is accidental, sort them directly:
jq -S '.tags |= sort' before.json > before.norm.json
When order is meaningful, leave it alone and accept that a reordering is a real finding.
Other differences that are not differences
A few more sources of phantom diffs, worth normalising away before you go looking for a cause.
Number formatting. 1.0, 1, and 1e0 are the same number and different text. A round trip through a parser that prints canonically collapses them, which jq . does.
Unicode escaping. "café" and "café" are the same string. Different serialisers choose differently. A parse and reprint settles it.
Trailing whitespace and line endings. A file written on Windows and one written on Linux differ on every single line to a byte oriented diff. Normalise line endings first.
Timestamps and generated identifiers. Fields such as requestId, generatedAt, or a signature will differ on every run by design. Strip them rather than reading past them each time:
jq -S 'del(.requestId, .generatedAt)' before.json > before.norm.json
Deleting the fields you expect to change is what turns a noisy comparison into a regression test you can actually run on a schedule.
When the two documents are different formats
Comparing a YAML config against the JSON it compiles to, or a TOML file against its JSON equivalent, is the same problem with one extra step: convert both to JSON first, then normalise, then diff. The YAML to JSON converter and the JSON and TOML converter handle the conversion in the browser.
This is worth doing when reviewing a configuration change. YAML in particular has enough syntax that a change can look larger or smaller than it is, and a value such as no or 1.0 can quietly change type on the way through. Comparing the parsed result rather than the source text shows what the application will actually see. The YAML gotchas post covers why that matters more than it sounds.
A practical sequence
- Parse and reprint both documents with sorted keys and consistent indentation.
- Delete fields known to change on every run.
- Sort any array whose order is accidental, by a stable key.
- Diff the results.
- Read what remains, which should now be only real changes.
Steps one and two remove most of the noise. Step three is the one that needs a decision rather than a command, and it is the reason this cannot be fully automated.