How to Compare Two JSON Files

Learn why a plain text diff is noisy for JSON, how a structural JSON diff ignores key order and whitespace, and how to read the result.

Comparing two JSON files with a text diff often lights up the whole file, because a different indent or key order changes every line. A structural comparison shows only what actually changed.

Why a text diff is noisy for JSON

A line-based diff treats JSON as plain text. If one file is minified and the other is pretty-printed, or if a serializer writes keys in a different order, nearly every line is reported as changed even though the data is identical.

The same happens when two systems indent with different widths. None of these differences matter to a program that reads the JSON, so they should not matter in the comparison either.

Compare the data, not the text

A JSON diff parses both documents first and compares the resulting values. Object keys are sorted before comparing, so reordering keys is not a change, and whitespace disappears because it never reaches the parsed data.

Only real differences remain: a key that was added or removed, a value that changed, or an array item that was inserted, removed or edited.

Arrays are ordered

Unlike object keys, array items have a position. If an item moves from index 0 to index 2, the diff reports it as a change, because the array is a different list. If your arrays are really sets, sort them by a stable key before comparing.

Fixing invalid input

Both sides must be valid JSON before they can be compared. Trailing commas, single quotes and comments are the usual culprits. If the comparison reports which side is invalid, format that side first to find the exact line and column of the error.

Related tools

All guides