Sorting object keys alphabetically gives every JSON document a predictable shape. Two documents with the same data but keys in a different order become identical after sorting, which makes comparisons, code reviews and version-controlled files much easier to work with. This guide explains what sorting changes, how to do it, and when to avoid it.
null, and the order of items in arrays.According to the JSON specification, objects are unordered collections of name/value pairs, so a standards-compliant consumer treats the sorted and unsorted versions as the same data.
Before:
json{"z":1,"a":2,"b":{"y":1,"x":2}}
After sorting (formatted for readability):
json{ "a": 2, "b": { "x": 2, "y": 1 }, "z": 1 }
Notice that the nested object under "b" was sorted too.
In the browser: paste the JSON into the JSON Formatter and use the Sort button in the editor toolbar. You can sort the whole document and choose ascending or descending order.
With jq: the -S flag sorts keys recursively.
bashjq -S . input.json > sorted.json
In Python:
pythonimport json print(json.dumps(data, indent=2, sort_keys=True))
In JavaScript, JSON.stringify has no built-in option, so sort recursively:
javascriptfunction sortKeys(value) { if (Array.isArray(value)) return value.map(sortKeys); if (value && typeof value === 'object') { return Object.fromEntries( Object.keys(value).sort().map(k => [k, sortKeys(value[k])]) ); } return value; } const sorted = JSON.stringify(sortKeys(data), null, 2);
The function maps over arrays instead of sorting them, so array order is preserved.
{"id":1,"name":"a"} and another returns {"name":"a","id":1}, a text diff shows every line as changed. Sort both first, then compare the two JSON files.host next to port). Alphabetical sorting can make it harder to read, so consider sorting only for comparison and keeping the original file as it is.If an object contains the same key twice, most parsers keep only the last value. Sorting after parsing will therefore silently drop the earlier one. Duplicate keys are a bug worth fixing at the source; validate the document first with Validate JSON.