Sort JSON Keys Alphabetically: What Changes, What Doesn't, and When to Skip It
A practical review of sorting JSON keys into alphabetical order: what the transformation changes, where ordering rules differ, and when original key order should be kept.
Is alphabetical key order right for your use?
Sorting JSON keys alphabetically suits files that people compare, review or keep under version control, such as configuration files, test fixtures, API response snapshots and translation files. Its main benefit is predictability. Two documents with the same data produce the same key order, so diffs show real changes instead of reshuffled lines, and a given key is easier to find in a long object.
The main tradeoff is that sorting discards whatever order the author or producing system chose. That order may have been grouping related fields, putting an identifier first, or following a schema's logical flow. Sorting replaces meaningful human ordering with mechanical ordering. Keep the original order when a person reads the file top to bottom as documentation, when a consuming system depends on key position, or when you need a byte-for-byte record of what a system actually emitted.
What the transformation actually changes
This is a formatting transformation, not a character-level one. Nothing is reversed, mirrored or replaced with look-alike Unicode characters. A sorter parses the JSON into a data structure, orders the member names inside each object, and writes the result back out as text. Keys and values keep their exact spelling. Only the position of each name/value pair within its object moves.
The stored text does change. Line order, line numbers and file bytes all differ after sorting. The data model is meant to stay the same, because the JSON standard (RFC 8259) defines an object as an unordered collection of name/value pairs. A conforming consumer should treat sorted and unsorted versions as equivalent. In practice, the standard also notes that implementations differ in whether they expose member order, so equivalence depends on the software reading the file.
Arrays are not sorted. Array order is part of the data, so a correct key sorter leaves elements where they are and only sorts the keys of any objects inside them. In the example below, the nested object is sorted and the list keeps its original sequence.
Input:
{"b": 1, "a": {"d": 2, "c": 3}, "list": [3, 1, 2]}
Sorted (recursive):
{"a": {"c": 3, "d": 2}, "b": 1, "list": [3, 1, 2]}
What "alphabetical" means to most tools
Most JSON tools compare keys by character code, not by dictionary or locale rules. That produces results that can look wrong at first. All uppercase letters come before all lowercase letters, and some punctuation falls between the two groups. For example, the keys "a", "B" and "" sort as "B", "", "a", because B is code 66, the underscore is 95 and lowercase a is 97. Accented letters sort after the unaccented Latin alphabet, not alongside their base letters.
Tools also differ slightly in the unit they compare. Some compare Unicode code points, while JavaScript's default sort and the JSON Canonicalization Scheme (RFC 8785) compare UTF-16 code units. These approaches give the same result for ordinary ASCII keys. They can differ for keys containing characters outside the Basic Multilingual Plane, such as many emoji, relative to characters near the top of that plane. If two systems must produce identical output, use the same tool or a defined canonicalization scheme on both sides.
Recursive versus top-level sorting
Some tools sort only the outermost object and some sort every nested object. For diffing and consistency you usually want recursive sorting. Check which behavior a tool uses before relying on it. A top-level-only sort can leave deeply nested configuration in its original order without any warning.
Side effects of parse-and-rewrite sorting
Because sorting normally works by parsing and re-serializing, it can change more than key order. Before you sort data that matters, check for these issues:
- Duplicate keys: RFC 8259 says names should be unique but does not forbid duplicates. Many parsers keep only the last occurrence, so sorting can silently drop data that a different consumer would have read.
- Number formatting: a re-serializer may rewrite numbers, for example turning 1.0 into 1 or changing exponent notation. Parsers that store numbers as double-precision floats, including JavaScript's built-in parser, can lose precision on integers larger than 2^53. How a given tool handles this varies by tool and version.
- String escapes: escaped sequences such as \u00e9 may be written back as the literal character, or the reverse, depending on the serializer's settings.
- Whitespace and indentation: the output follows the tool's formatting, not the original layout.
- Comments and trailing commas: standard JSON does not allow them, so a strict parser will reject JSONC or JSON5 files, and a lenient one may strip comments when it rewrites the file.
- Integer-like keys in JavaScript: plain JavaScript objects always list keys that look like array indexes (such as "2" and "10") first, in numeric order, no matter what order you insert them in. A JavaScript-based sorter can therefore output "2", "10", "a" instead of the string order "10", "2", "a".
Will the result stay readable and usable after sharing?
Sorted JSON is still ordinary plain text in the same character encoding, so copying, pasting, searching and editing work the same way as for any other JSON. No special glyphs or presentation layers are involved, and screen readers and text editors handle it like the original file. The readability change is structural. Related fields that were grouped together may end up far apart. An identifier or type field that used to come first may now sit in the middle of the object, which can make it harder for a person scanning or listening to the file to understand it.
The bigger compatibility risk is consumers that depend on key order despite the standard. Examples include code that reads fields positionally, signature or hash checks computed over the exact original bytes, and some database or RPC command formats that expect a particular field first. Re-sorting a signed payload will break its signature even though the data is equivalent. No destination-specific testing was supplied for this review, so confirm how your own consumer behaves before you replace production data with sorted output.
A one-time sort of a file already in version control produces a large diff that hides the history of individual lines. Teams that adopt sorting often do it in a dedicated commit and then enforce it with a formatter so the order stays stable from then on.
Sorting keys locally
Pasting data into a web-based sorter sends it to a service whose handling you cannot verify from its interface, so prefer local tools for anything sensitive. Common command-line options include jq's -S flag and Python's built-in json.tool module with --sort-keys. Both sort recursively and leave arrays in their original order.
jq -S . input.json > sorted.json
python3 -m json.tool --sort-keys input.json sorted.json
In JavaScript, the built-in JSON.stringify has no sort option, so a small recursive helper is needed. The integer-like key caveat above still applies to this approach.
function sortKeys(value) {
if (Array.isArray(value)) return value.map(sortKeys);
if (value !== null && typeof value === "object") {
return Object.fromEntries(
Object.keys(value).sort().map((key) => [key, sortKeys(value[key])])
);
}
return value;
}
const sorted = JSON.stringify(sortKeys(JSON.parse(text)), null, 2);
Gaps in this review
No specific tool, version or destination was tested for this article. The behaviors described come from the JSON standards and the general way common tools document their sorting. Precise handling of large numbers, escapes and duplicate keys varies by implementation, so run a quick round-trip check on representative data with the exact tool you plan to use.