What gets sorted
Object keys are sorted at every depth. Arrays keep their element order — sorting array items would change semantics. The result is re-serialized with two-space indentation so it can be compared directly.
- Ascending uses locale-independent comparison, so
Asorts beforeaconsistently. - Descending reverses the key order but leaves arrays untouched.
- Integer-like keys are always enumerated first by JavaScript engines, regardless of sort; this is a language limitation.
Why deterministic JSON matters
Configuration checksums, cache keys, signed payloads and snapshot tests all depend on stable serialization. Sorting keys is the simplest way to get it without adopting canonical JSON or a signing scheme.
If a signature depends on key order, sorting is not enough — you need a canonicalization scheme such as JCS (RFC 8785), which also normalizes numbers and strings.