Skip to main content
CuteJSON
↑↓ Navigate Enter Select Esc Close

How to sort JSON keys for a clean diff

Published 2 min read By Akash Kinkar Pandey

Two documents that hold the same data in a different key order are impossible to compare with a plain text diff. Configuration written by hand and configuration written by a program almost never agree on order, and sorting both the same way is what makes them comparable again.

Using the JSON key sorter

Choose an order, A to Z or Z to A, an indent width, and press Sort keys. Only object keys move. An array is left exactly as it was written, because an array’s order is part of the data it holds, not an accident of how it was typed, and a tool that quietly reordered arrays too would change what the document means while claiming only to tidy it.

Sorting

{"item10":"a","item2":"b","Zebra":"c","apple":"d","list":[3,1,2]}

by default returns keys in exact character code order: Zebra before apple (capital letters sort before lower case ones), and item10 before item2 ("1" is a smaller character than "2"). The array [3, 1, 2] comes back completely untouched.

The “Numbers in order” option

Character code order is why item10 sorts before item2: the comparison looks at one character at a time and never notices that 10 is bigger than 2. Turning on “Numbers in order” reads runs of digits as numbers instead, so item2 correctly comes before item10. This is written out explicitly in the tool rather than handed to the browser’s locale-aware comparison, because a comparison that follows the page’s language would sort the exact same file differently on the Hindi page than on the English one, and a tool that tidies a document has to give the same answer regardless of who is using it.

Duplicate keys

A document with a duplicate key keeps both copies, side by side, after sorting. This tool does not decide which one is “correct” the way a JSON.parse based approach would by silently keeping only the last one; it sorts what is there and leaves the decision about the duplicate to you, or to the JSON validator, which will flag it as a warning.

Why sorting does not change your data

Sorted or not, the values, their types and their exact text are identical. This is a display and comparison convenience, not a transformation of the document’s meaning, which is why it is safe to sort a document before comparing it in the JSON diff tool without worrying that the sort itself introduced a difference.

Back to all posts