To sort JSON keys alphabetically, run jq -S . file.json on the command line, call json.dumps(data, sort_keys=True) in Python, or rebuild each object from its sorted keys in JavaScript. All three sort nested objects and leave arrays alone. The results differ in small ways, though: number-like keys and capital letters can land in different places depending on the tool.
Why sort JSON keys at all
Sorting JSON keys gives the same data one fixed text form. Two API responses with the same values but different key order then look identical in a diff, hash to the same value, and stop creating noise in code review.
The order itself carries no meaning. If you're unsure whether your consumer cares, does JSON key order matter covers the spec and the places where order does bite. If all you need is to compare two files, you may not need to sort them at all: see comparing JSON while ignoring key order.
Sort JSON keys alphabetically with jq on the command line
jq sorts keys with one flag. The jq manual describes --sort-keys (short form -S) as printing "the fields of each object with the keys in sorted order", and it applies to every object at every level.
jq -S . config.json > config.sorted.json
The . filter passes the input through untouched, so the only change is key order and indentation. jq compares keys by Unicode code point. So Zebra sorts before apple: capital letters have lower code points than small letters.
Sort JSON keys in Python with sort_keys
Python's built-in json module sorts keys when you pass sort_keys=True. The json module docs say that with it set, "dictionaries will be outputted sorted by key", and the default is False.
import json
with open("config.json") as f:
data = json.load(f)
print(json.dumps(data, sort_keys=True, indent=2))
Nested dictionaries are sorted too. One detail trips people up: the sort happens before keys become strings. A dict built in Python code with integer keys {10: "a", 2: "b"} comes out as "2" then "10", sorted by numeric value. Keys that arrived from a JSON file are already strings, so "10" sorts before "2" there.
Sort JSON keys in JavaScript with a recursive function
JavaScript has no built-in option for sorted output, so you rebuild each object with its keys in order. JSON.stringify visits properties in the same order as Object.keys(), according to the JSON.stringify reference, so a rebuilt object prints in the new order.
function 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(JSON.parse(text)), null, 2);
The function walks into arrays so objects inside them get sorted, but it keeps the array items in place. The default sort() compares strings by UTF-16 code units, per the Array sort reference, so capitals again come before small letters.
You'll see a shortcut on forums: passing a sorted key list as the second argument to JSON.stringify. Don't use it for sorting. That argument is an allow-list of properties to include, so a key that exists only in a nested object gets dropped unless you remember to list it.
Why JavaScript can't fully sort number-like keys
JavaScript objects always list integer-like keys first, so a JS sort cannot fully match jq or Python. The for...in reference states that non-negative integer keys are traversed first "in ascending order by value", and only then the other string keys in the order they were created.
This is the main limitation of the JavaScript approach. You can insert keys in perfect string order and the engine will still move "2" and "10" to the front, in numeric order. Here is one input run through each method:
Input: {"b": 1, "10": 2, "2": 3, "B": 4}
| Method | Output key order | Why |
|---|---|---|
jq -S |
10, 2, B, b |
Code point order on strings |
Python sort_keys=True (keys from a JSON file) |
10, 2, B, b |
Keys are already strings |
JavaScript sortKeys() above |
2, 10, B, b |
Integer keys forced first, numeric order |
Go json.Marshal on a map[string]any |
10, 2, B, b |
Map keys are sorted as strings |
If your keys are IDs like "2" and "10", and the sorted text has to match output from another language byte for byte, sort with jq or Python, or write the JSON text yourself instead of going through a JS object.
Sort JSON keys in Go and Java
Go sorts map keys for you. The encoding/json docs say that when a map is marshaled, "the map keys are sorted and used as JSON object keys", with integer keys converted to strings. The same page warns that the v2 package marshals maps in a non-deterministic order, so don't count on sorting there.
Java with Jackson needs two settings, because they cover different things:
SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYSsortsjava.util.Mapentries by key. It's off by default, per the serialization features list.MapperFeature.SORT_PROPERTIES_ALPHABETICALLYorders the fields of your own classes. The mapper features list notes it applies only to POJO fields and does not apply to Map serialization.
Turn on both if your output mixes plain classes and maps.
How to check the sort worked
A sorted file should keep the same data and only change its order. To confirm:
- Run the sorted file through the same tool a second time.
- Check that the second pass changes nothing.
- Diff two sorted files line by line. With keys in a fixed order and the same indentation, matching data lines up row for row, so a line-by-line diff checker shows only real value changes.
- Make sure array lengths and element order match the original.
Common mistakes when sorting JSON keys
Most sorting bugs come from sorting too little or too much. These are the ones I see most often:
- Sorting only the top level.
Object.keys(obj).sort()without recursion leaves nested objects untouched. - Sorting arrays. Array order is data. The JSON canonicalization standard sorts object members recursively but says array element order "MUST NOT be changed".
- Expecting dictionary order. Tools compare code units, not words, and the canonical form does it "independent of locale settings". Lowercase the keys yourself if you want case-insensitive order, and accept that the output then isn't canonical.
- Hashing sorted output that still varies. Sorting fixes key order, but whitespace and number formatting can still differ. For signatures, follow the full canonicalization rules, not sorting alone.
For more on keeping output stable, see tabs vs spaces in JSON.stringify and formatting JSON in VS Code.
FAQ
How do I sort JSON keys from the command line?
Use jq with the -S (--sort-keys) flag, for example jq -S . input.json > sorted.json. It sorts the keys of every object, at every level.
Does sorting JSON keys change the data?
No. A JSON object is an unordered set of name/value pairs, so the sorted file holds the same data. Only the text changes, which is why sorted files diff and hash consistently.
Are arrays sorted when I sort JSON keys?
No. Key sorting only reorders object members. Array element order is part of the data, and the JSON canonicalization standard says array order must not change.
Why are uppercase keys listed before lowercase ones?
Most tools compare raw character codes, not dictionary order. Capital letters have lower code values than small letters, so Zebra comes before apple.
Why does my JavaScript sort put number keys first?
JavaScript objects always list non-negative integer keys first, in numeric order, no matter the order you insert them. A JS-only sort cannot place them anywhere else.