All articles

JSON Sort Keys: why sort an object's keys

The JSON specification doesn't formally define key order in an object — {"a": 1, "b": 2} and {"b": 2, "a": 1} represent the same data. In practice, though, key order still matters quite often, both for people and for tools that work with that data.

Why sort keys

  • Diffing. If two JSON documents with identical data have different key orders, a text diff will show a false difference. Sorting removes that problem.
  • Deterministic output. If the same object gets serialized multiple times — say, to generate a hash or a cache key — sorted keys guarantee the same result every time.
  • Readability. An alphabetically sorted object is easier to scan and find a specific field in, especially in large structures.

Recursive sorting

To make the result predictable, sorting is usually applied recursively — not just to top-level keys, but to the keys of every nested object at any depth. Array element order stays untouched, since for arrays, element order is a meaningful part of the data.

When you don't need it

If the JSON is only ever consumed by a program, not a human or a diff tool, sorting keys usually provides no practical benefit — parsers read an object the same way regardless of field order.

The gotcha that's there before you even reach other alphabets

Even plain English text has a sorting surprise baked in: a naive code-point sort compares characters by their raw ASCII value, and every uppercase letter (A–Z, 65–90) sits below every lowercase letter (a–z, 97–122) in that table. So keys like "Zebra" and "apple" sort as "Zebra" first, even though a real dictionary would put "apple" ahead of "zebra" — the naive sort is case-sensitive, not truly alphabetical. This is the baseline gotcha worth understanding before non-Latin scripts add their own layer of complexity on top.

Sorting and locale

Alphabetical sorting of keys that contain more than Latin letters depends on whether characters are compared byte-by-byte (Unicode code point) or with locale-aware collation. For example, a code-point comparison puts uppercase letters before lowercase ones regardless of alphabet, while locale-aware sorting may order keys differently — worth keeping in mind if the result is compared across different languages or systems.

Try the tool