Skip to content
gohacks.dev
Standard Library

Sort JSON Keys

Sort the keys of a JSON object alphabetically at every nesting level, in natural or plain order, ascending or descending, with optional array sorting.

Free · No sign-up · Your inputs stay in your browser

Input

Sort JSON keys alphabetically

Output

Sorted JSON

209 characters

Keys are sorted at every depth so two documents with the same data diff cleanly. Arrays keep their order unless you ask, because in most JSON the order of a list is meaning. Integer-like keys are always listed first by JavaScript itself, whatever the sort.

Runs in this browser. Nothing you paste is sent to a server.

Why sort keys

JSON objects are unordered, but files are diffed line by line. Two documents with the same data in a different key order produce a diff full of noise, and sorted keys make config files, snapshots and API fixtures stable under version control. jq -S . does the same in a terminal, and many serialisers (Python's json.dumps(sort_keys=True)) have an option for it.

Integer-like keys

JavaScript objects always list integer-like keys (such as "1" or "42") first, in numeric order, regardless of insertion. Any sort done in a JavaScript runtime, this one included, ends up with them first.

Share

Frequently asked questions

Should I sort arrays as well?
Usually not. Array order is often meaningful, such as steps, priorities or a list of migrations. Sort arrays only when they are sets of plain values, such as tags.
Does sorting change the meaning of the JSON?
Not for objects: the JSON specification does not assign meaning to key order. It does change arrays, which is why array sorting is off by default.
Is what I paste sent anywhere?
No. The tool runs entirely in your browser with JavaScript. Nothing you type or paste is sent to our server or stored.

Keep planning

Similar tools