Sorting JSON keys: when it helps
Sorting object keys alphabetically can make comparisons and code reviews significantly easier.
What sorting changes (and what it doesn’t)
- Changes: the order of keys inside objects
- Doesn’t change: values, numbers, strings, booleans, arrays, and nested objects
Example
Before:
{"z":1,"a":2,"b":{"y":1,"x":2}}
After sorting:
{"a":2,"b":{"x":2,"y":1},"z":1}
When it’s safe
- API payloads where order is not meaningful
- Configuration objects consumed by typical JSON parsers
- Making diffs cleaner before using a JSON diff tool
When to be careful
- Non-standard consumers that incorrectly treat key order as meaningful
- Signed payloads where the exact byte representation matters
- Arrays: element order can be meaningful; don’t reorder arrays unless you’re sure
Related: Compare JSON · Pretty print JSON