Why Sort JSON Keys?
Sorting JSON keys alphabetically produces a canonical form of the data — the same object always serializes to the same string regardless of the order keys were added. This matters enormously for version control: unsorted JSON in git shows noisy diffs every time a key is inserted anywhere, even when no values changed. Sorted JSON produces clean, minimal diffs where only real data changes are visible.
The second big use case is snapshot testing. Frameworks like Jest and Vitest compare stringified JSON — if key order varies between test runs (which it can in Node.js on older versions, or when data comes from different sources), tests flake. Sorting eliminates the noise. The third use case is content hashing: computing a stable hash of a JSON payload requires deterministic key ordering, otherwise two logically-equivalent objects hash differently.
How to Sort JSON Keys in Different Languages
JavaScript / Node.js
// Sort top-level keys only
const raw = { name: 'Alice', age: 30, city: 'NYC' };
const sorted = JSON.stringify(raw, Object.keys(raw).sort(), 2);
// Deep-sort nested objects (recursive)
function deepSortKeys(obj) {
if (Array.isArray(obj)) return obj.map(deepSortKeys);
if (obj && typeof obj === 'object') {
return Object.keys(obj).sort().reduce((acc, k) => {
acc[k] = deepSortKeys(obj[k]);
return acc;
}, {});
}
return obj;
}
console.log(JSON.stringify(deepSortKeys(data), null, 2));Python
import json
# sort_keys=True sorts at every nesting level automatically
data = {'name': 'Alice', 'age': 30, 'city': 'NYC'}
print(json.dumps(data, indent=2, sort_keys=True))
# For arrays of objects, sort_keys sorts keys inside each object,
# but does NOT reorder the array items themselves
records = [{'z': 1, 'a': 2}, {'y': 3, 'b': 4}]
print(json.dumps(records, indent=2, sort_keys=True))Command Line (jq)
# --sort-keys (or -S) sorts keys at every level
jq --sort-keys . input.json > sorted.json
# Combine with normalization for canonical output
jq -S -c . input.json > canonical.json
# Sort keys in a curl response
curl -s https://api.example.com/data | jq -S .Preserving Arrays While Sorting
A common mistake is expecting sort_keys=True or the recursive sort above to also sort array contents. It does not, and it should not. Arrays in JSON represent ordered sequences — [1, 2, 3] is not the same as [3, 2, 1]. Sorting the elements would corrupt data whose meaning depends on order (like a list of transactions or steps in a workflow).
What the sort operation does inside arrays is sort the keys of each object element. So [{ b: 2, a: 1 }, { d: 4, c: 3 }] becomes [{ a: 1, b: 2 }, { c: 3, d: 4 }] — array order preserved, object keys sorted. If you actually need to sort array items themselves, that's a separate operation and depends on the value type (numeric sort, string sort, sort by a specific object field).
When NOT to Sort JSON Keys
Some JSON has semantic key order. OpenAPI / Swagger specs use conventions where openapi, info, paths appear in a specific order for human readability. package.json traditionally starts with name, version, description — npm even preserves this order in some tooling. tsconfig.json and similar config files often group related options together.
Sorting these alphabetically technically produces valid JSON but breaks conventions the community relies on. For these files, use a formatter that preserves order (the default in this tool) rather than the sort variant. Sorting is best reserved for machine-generated data, API payloads used in tests, and canonical hashing.
Common Pitfalls
1. Sort is locale-sensitive by default in some tools. JavaScript's Array.prototype.sort() uses code-point comparison by default (which is what you want for JSON), but localeCompare would reorder based on locale rules — producing different results in different regions. Stick with the default sort for JSON canonicalization.
2. Numeric-string keys sort as strings, not numbers. Keys "1", "10", "2" sort to "1", "10", "2" — not "1", "2", "10". This is correct behavior per JSON spec (keys are strings) but can surprise developers. If numeric ordering matters, convert to an array with an index field.
3. Special characters in keys. Keys with underscores, dollar signs, or unicode characters sort by their code points — which may not match human expectations. "_id" sorts before "name" because _ (0x5F) comes before a (0x61).
Related JSON Tools
- JSON Formatter (Parent Tool) — the underlying formatter used by every variant
- Format JSON Online — general-purpose beautifier with 2/4-space and tab options
- Minify JSON Online — strip whitespace for production payloads
- JSON Validator — validate without formatting
- JSON Diff Checker — compare two JSON objects side-by-side