Sorting JSON keys so two files can be compared
The keys of a JSON object have no meaning in their order. {"id": 7, "name": "Ada"} and {"name": "Ada", "id": 7} are the same object to every JSON reader. But they are different text, and text is what diff tools, code review and version control compare. Two services that write the same data in different key orders produce files that look completely changed. Sorting the keys of both files first removes that noise, so a diff shows only the values that really differ.
This tool sorts at every level. The top-level object is sorted, then each object inside it, then each object inside those, down to the deepest level. Arrays are walked into, so an array of user records has the keys of every record sorted, but the array itself is not reordered. That is deliberate. In JSON, the order of an array is part of its value: a list of steps, a ranking or a timeline means something different when it is shuffled.
There are two ways to compare keys. Like jq -S compares them by character code, one UTF-16 unit at a time. That is the order jq -S, Python's json.dumps(sort_keys=True) and the JSON Canonicalization Scheme (RFC 8785) produce, so use it when the result must match another program byte for byte, or when you are building canonical JSON to hash or sign. Its rules surprise people: all uppercase letters come before all lowercase letters, and "10" comes before "2" because "1" is a smaller character than "2". Natural ordering fixes both. It ignores case and reads runs of digits as numbers, so "step2" comes before "step10", which is what a person reading a translation file expects.
Sorting through JSON.parse would damage the data in two ways, which is why this tool uses its own parser. JSON.parse rounds numbers longer than about 16 digits, so a 64-bit ID changes. It also keeps only the last copy of a key written twice. Here every number keeps its digits, and a duplicate key keeps both copies, in the order they were written, because the sort is stable.
The output is indented with two spaces by default, or written on one line if you want a compact canonical form. Either way the values are untouched: only the order of keys inside objects changes. Everything runs on this page, so configuration files and API responses with private data are never uploaded.