{ }jsonkitOpen the tool

How to Sort JSON Keys Alphabetically (and Make JSON Canonical)

7 min read · updated 2026-07-12

Two JSON files can hold exactly the same data yet look completely different, purely because their keys are in a different order. That makes diffs noisy, defeats caching, and produces different hashes for identical data. Sorting keys — producing *canonical* JSON — fixes all three.

This guide explains why JSON key order carries no meaning, how to sort object keys alphabetically (recursively, at every level), what canonical JSON is and why hashing and signing depend on it, and the one thing sorting must never touch: array order.

Why JSON Key Order Doesn't Matter (Semantically)

The JSON specification, RFC 8259, is explicit: an object is an *unordered* collection of name/value pairs. {"a":1,"b":2} and {"b":2,"a":1} are, by the standard, the same object. Any conforming parser must treat them as equal, so no correct program should depend on the order keys appear in.

That is the theory, and it is why reordering keys is always a safe, lossless transformation — you are not changing the data, only its presentation. (In practice most parsers *preserve* insertion order when you read an object back, which is convenient but is a convenience, not a guarantee you should rely on for correctness.)

Why Sort Keys at All?

If order is meaningless, why bother sorting? Because *humans and tools* care about consistency even when the data model does not. A stable, predictable key order buys you several concrete wins:

  • Clean diffs. When two versions of a file both have sorted keys, a diff shows only real changes — not a field that merely moved. This is the biggest everyday payoff. Compare two files with our JSON diff guide.
  • Stable hashes. Hashing identical data must give an identical digest. Since serialization order changes the bytes, you must sort keys first or two equal objects hash differently.
  • Reliable caching & deduplication. Using a serialized object as a cache key or dedup fingerprint only works if equal objects always serialize the same way.
  • Readability. Alphabetized keys make large config files and API payloads easier to scan and to locate a field in.

Sorting Keys in Code

The core idea is to walk the structure, and at every object, rebuild it with its keys in sorted order. Crucially this has to be recursive — a shallow sort only orders the top level and leaves nested objects untouched. Arrays are walked into (to sort objects inside them) but their element order is preserved.

Recursive key sort — nested objects sorted, array order preserved.js
function sortKeys(value) {
  if (Array.isArray(value)) {
    // Recurse into elements, but KEEP array order.
    return value.map(sortKeys);
  }
  if (value && typeof value === "object") {
    return Object.keys(value)
      .sort() // alphabetical by key
      .reduce((acc, key) => {
        acc[key] = sortKeys(value[key]);
        return acc;
      }, {});
  }
  return value; // primitives unchanged
}

const data = { b: 1, a: { d: 4, c: 3 }, list: [{ z: 1, y: 2 }] };
console.log(JSON.stringify(sortKeys(data)));
// {"a":{"c":3,"d":4},"b":1,"list":[{"y":2,"z":1}]}

Note that JSON.stringify also accepts an array of keys as its second argument, but that is a *whitelist* that drops any key you don't list — not a general sort. For a true canonical output you sort the structure first, as above, then stringify.

What Canonical JSON Actually Means

Sorting keys is the headline step toward canonical JSON — a single, deterministic serialization of a given piece of data, so that equal data always produces byte-for-byte identical output. Canonicalization matters most for cryptography: to hash, sign, or verify JSON, both sides must serialize it exactly the same way, or the digests won't match even though the data does.

A full canonical form pins down more than key order. Formal schemes like JCS (JSON Canonicalization Scheme, RFC 8785) also specify number formatting, string escaping, and whitespace. For everyday diffing and caching you rarely need the full standard — sorted keys plus consistent whitespace usually suffice — but the goal is the same: remove every meaningless difference so the only remaining differences are real.

  • Key order — sorted, recursively (the main lever).
  • Whitespace — fixed (typically minified) so formatting can't vary. See how to minify JSON.
  • Number & string formatting — one representation per value (what full schemes like JCS nail down).

Sort JSON Keys Without Writing Code

For a one-off file, a config you want alphabetized, or two payloads you're about to compare, you don't need a script. Paste the JSON, sort the keys, and copy the result back out. Because the transformation is lossless — only order changes — it's safe to run on any valid JSON.

A client-side sorter does this entirely in your browser: the JSON is never uploaded, which matters when the payload holds tokens, keys, or personal data. Sort both versions of a file the same way and a JSON diff will then show only the substantive changes.

a→zJSON SorterOpen the tool

A typical workflow: sort keys to canonicalize, minify to fix whitespace, then hash or diff the stable result. Each step strips away a source of meaningless variation so the comparison reflects the data itself.

Frequently asked questions

Does the order of keys matter in JSON?

Not semantically. RFC 8259 defines a JSON object as an unordered set of name/value pairs, so {"a":1,"b":2} and {"b":2,"a":1} represent the same object and every conforming parser treats them as equal. Order matters only for presentation and for byte-level operations like diffing, hashing, and caching — which is exactly why you sort keys.

How do I sort JSON keys alphabetically?

Walk the structure recursively: at each object, rebuild it with Object.keys(obj).sort(), and recurse into values so nested objects are sorted too. Leave arrays in their original order — only their inner objects get sorted. Then serialize with JSON.stringify. Or paste the JSON into a key-sorter tool that does it for you.

Does sorting JSON keys change the data?

No. Because object key order carries no meaning in JSON, reordering keys is a lossless transformation — the parsed data is identical. The only thing that changes is the serialized text. This is why it's safe to sort keys on any valid JSON, including before diffing or hashing.

Should sorting reorder array elements too?

No — never. JSON arrays are ordered, so [1,2,3] and [3,2,1] are genuinely different values. 'Sorting JSON' means sorting object keys only. A correct sorter recurses into arrays to sort any objects inside them but keeps the elements in their original positions.

What is canonical JSON?

A canonical (or normalized) JSON serialization is a single deterministic output for a given piece of data, so equal data always produces byte-for-byte identical text. It fixes key order (sorted), whitespace, and number/string formatting. Formal schemes like JCS (RFC 8785) specify all of this; for everyday use, sorted keys plus consistent whitespace is usually enough.

Why do I need to sort keys before hashing JSON?

A hash or signature is computed over bytes, and serialization order changes the bytes. Two objects with the same data but different key order produce different serialized strings and therefore different digests, so a signature over one won't verify against the other. Canonicalizing first — sorting keys and fixing whitespace — makes the bytes deterministic so hashes match.