Developer Formatting

JSON key sorter

What to do
Indent

Processed in your browser · nothing is uploaded

Local · arrays keep their order, deliberately
Advertisement
320 × 100

Sorts object keys alphabetically at every level of nesting. Values, and the order of arrays, are untouched.

How to use the json key sorter

1 Paste the JSON. Keys are sorted at every level of nesting.
2 Set the indent to match whatever you are comparing against.
3 Sort both documents the same way, then diff them.
4 Copy the result, or save it as a file.

The reason to do this is diffing. Key order carries no meaning in JSON, but it means everything to a text diff; two objects with identical data serialised by different languages produce a diff that appears to change every line. Sorting both first reduces that to the differences that are real. It is also the cheap way to make a config file reviewable in a pull request. One thing deliberately not done: array order is significant in JSON, so sorting an array would change the data rather than its presentation.

The order used is dictionary order rather than byte order, so apple comes before Apple before zebra, and accented keys sort next to their base letters. That matters when the other side of your diff was sorted somewhere else: Python’s sort_keys=True orders by code point and puts every capital letter ahead of every lowercase one, so the two will disagree on any document with mixed-case keys. Sort both with the same tool or not at all.

One result surprises people every time. Keys that look like non-negative integers are not sorted with the rest: they are listed first, in ascending numeric order, because that is how JavaScript objects order their keys and nothing here can override it. A document keyed by ID comes back with 2 before 10, and the lettered keys follow alphabetically after all of them.

Sorting also parses and re-emits, which has one consequence beyond formatting: a document with the same key twice keeps only the last occurrence, because the duplicate is resolved during the parse. That is a change to the data rather than to its presentation, so it is worth knowing before running this over a file you did not write.

Questions

Not to the standard or to any parser. It matters a great deal to a text diff, which is why sorting helps.

ECMA-404; the JSON data interchange syntaxMDN, JSON.parse()
Advertisement
300 × 250
Was this tool any good?
Internal signal only · I use it to find the tools worth rebuilding