Home / Guides

Comparing JSON correctly: key order, duplicate keys and numbers over 2^53

Two JSON documents can hold the same data and look different, or look the same and hold different data. The JSON standard explains both cases. One of them hides changed IDs from any comparison built on the standard JSON parser of JavaScript.

Key order does not matter, array order does

RFC 8259, the JSON standard, says: "An object is an unordered collection of zero or more name/value pairs", while "An array is an ordered sequence of zero or more values." So {"a":1,"b":2} and {"b":2,"a":1} are the same data, but [1,2] and [2,1] are not. A plain text diff reports the first pair as different; a JSON-aware comparison should not.

Arrays are trickier in practice: a list of tags or permissions is often a set where order means nothing. The JSON compare on this site respects array order by default and has an option to ignore it. When an item is inserted at the start of an array, it lines items up by content, so the rest of the array is not reported as changed.

Numbers over 2^53: the hidden trap

The standard warns that software commonly stores numbers as IEEE 754 double precision values and that integers "in the range [-(2**53)+1, (2**53)-1] are interoperable". That upper limit is 9,007,199,254,740,991, sixteen digits. Larger integers are common: database IDs, social media post IDs, order and tracking numbers.

JavaScript reads every JSON number as a double. We checked: JSON.parse turns both 12345678901234567890 and 12345678901234567891 into 12345678901234567000. A JSON comparison built on JSON.parse therefore reports two different IDs as equal. Our JSON compare reads numbers with its own parser: any number with more digits than a double can hold is kept as exact text and compared digit by digit, and the summary says how many such numbers it found.

Duplicate keys

The standard says names within an object "SHOULD be unique", and when they are not, "the behavior of software that receives such an object is unpredictable. Many implementations report the last name/value pair only." So {"price": 10, "price": 12} may read as 12 in one program and fail in another. Before comparing, make sure neither file repeats a key at the same level; a diff of the raw text shows them.

Types matter

1 and "1" are different values (a number and a string), and so are null, an empty string and a missing key. A good comparison reports a type change separately from a value change. 1, 1.0 and 1e0 are the same number.

A checklist for comparing JSON

  1. Format both sides the same way (the Format button) so a text view is readable.
  2. Compare by structure, not by text, so key order and spacing do not count.
  3. Decide whether array order matters for this data.
  4. Ignore keys that always change, such as timestamps or request IDs (the Ignore keys field).
  5. Watch for long IDs, duplicate keys and type changes.

Tools for this

Sources