JSON key order: why numeric keys jump ahead
Updated
Parse {"b":1,"10":2,"2":3} in JavaScript and print it back: you get {"2":3,"10":2,"b":1}. Nothing is broken. JavaScript lists integer-like keys first, in ascending numeric order, and everything else in the order it was added. Here is the exact rule, why sorting tools put "10" before "2" instead, what RFC 8259 says about order, and when order actually matters.
Why JavaScript reorders numeric keys
The order comes from the language, not from JSON. When JavaScript lists an object’s own keys (OrdinaryOwnPropertyKeys in the ECMAScript specification), it returns three groups: first the keys that look like array indices, meaning canonical integers from 0 to 2^32 − 2, in ascending numeric order; then all other string keys in the order they were created; then symbols. JSON.parse creates the properties in document order, but Object.keys, for loops, JSON.stringify and the console all use this listing.
const data = JSON.parse('{"b":1,"10":2,"2":3,"a":4,"01":5,"-1":6}');
Object.keys(data); // ['2', '10', 'b', 'a', '01', '-1']
JSON.stringify(data); // '{"2":3,"10":2,"b":1,"a":4,"01":5,"-1":6}'"01" and "-1" stay where they were: they aren’t canonical array indices, and neither are "1.5" or "4294967295". That’s why an object keyed by IDs, years or HTTP status codes comes back sorted numerically while the rest of it keeps its order. A reviver doesn’t help: it sees the keys already reordered.
Why sorting tools put “10” before “2”
Tools that sort keys compare them as text, character by character, and 1 comes before 2. So jq -S, Python’s sort_keys=True, Go’s encoding/json for maps, Jackson’s SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS and the Sort keys option on this site all print "10" before "2", and "B" before "b". The same document can come out as 2, 10 from JavaScript and 10, 2 from a sorter. Neither is wrong.
Python has a twist: when a dict has integer keys, sort_keys=True sorts them as numbers before turning them into strings, so {10: "a", 2: "b"} becomes {"2": "b", "10": "a"}. Mixing int and str keys raises TypeError: '<' not supported between instances of 'str' and 'int'.
What RFC 8259 says about order
Section 1 is short: “An object is an unordered collection of zero or more name/value pairs.” Section 4 adds that parsing libraries “have been observed to differ as to whether or not they make the ordering of object members visible to calling software”, and that code which doesn’t depend on member ordering will be interoperable.
So the text of a document has an order, but the data model doesn’t promise to keep it. Code that relies on key order relies on its parser, not on JSON. Arrays are different: their order is part of the value. Duplicate keys are a related trap: JavaScript and Python keep the first key’s position and the last key’s value, so {"a":1,"b":2,"a":3} reads as {"a":3,"b":2}.
Python, Go, Java and jq
| Parser | Order after parsing | Sorted output |
|---|---|---|
JavaScript JSON.parse | Integer-like keys first, ascending; the rest as written | No option; sort the keys yourself |
Python json | As written: a dict keeps insertion order | sort_keys=True, as text |
Go encoding/json | Structs: field declaration order. Maps: no order | Maps are always written sorted, as text |
| Java, Jackson | As written (LinkedHashMap, ObjectNode) | ORDER_MAP_ENTRIES_BY_KEYS, as text |
| jq 1.7 | As written | -S, as text |
| JSON Statham | As written, numeric keys included | Sort keys, by character code |
import json
data = json.loads('{"b": 1, "10": 2, "2": 3}')
list(data) # ['b', '10', '2']
json.dumps(data, sort_keys=True) # '{"10": 2, "2": 3, "b": 1}'var m map[string]int
if err := json.Unmarshal([]byte(`{"b":1,"10":2,"2":3}`), &m); err != nil {
log.Fatal(err)
}
out, _ := json.Marshal(m)
fmt.Println(string(out)) // {"10":2,"2":3,"b":1}json.Marshal documents the sorting of map keys. To keep the input order in Go, read the object token by token with Decoder.Token, or keep it as json.RawMessage and pass the bytes through untouched.
When key order matters
- Signatures and hashes over the body. Parse and re-serialize, and the bytes change even when the data doesn’t. Sign the exact bytes, or agree on a canonical form such as RFC 8785, which sorts keys by UTF-16 code units.
- Diffs and code review. A reordered file shows changes nobody made. JSON Diff compares objects by key and ignores their order.
- Files people read: configs, fixtures, API examples. Keep a logical order with
idandnamefirst, or sort consistently with Sort keys in the Formatter. - Streaming readers that expect a type field before the rest of the object. Write it first, and don’t let a reformatting step move it.
- Order that carries meaning, such as steps or a ranking. That belongs in an array:
[{"id":"10"},{"id":"2"}]keeps its order in every parser.
Key order on this site
The Formatter, the Minifier, JSON to YAML and the tree view keep keys in the order of your text, numeric keys included, because none of them goes through JSON.parse. Sorting is opt-in and sorts by character code at every level. Diff ignores key order. To see it, open the Formatter’s Sample menu and pick Precision test: "10" stays before "2".
JSON key order FAQ
Does JSON preserve key order?
The text has an order, but RFC 8259 calls an object unordered, so a parser may keep it, sort it or change it. Python, Jackson and jq keep it; JavaScript moves integer-like keys first; Go maps lose it.
How do I stop JavaScript from moving numeric keys?
Not with a plain object: the order is part of the language. Send an array of pairs, prefix the keys ("id10"), or keep the data as text and read it with a parser that preserves order.
Does sorting keys change the data?
No. The same names map to the same values, so any JSON reader sees the same data. The bytes do change, which matters for signatures, hashes and line-based diffs.
Why does Go sort my keys?
encoding/json writes maps in sorted key order so that the output is stable: a Go map has no order to keep. Use a struct if you need a fixed order; its fields are written in declaration order.