How to Sort JSON: Object Keys and Arrays of Objects

Data modeling 7 min readUpdated October 12, 2026

"Sorting JSON" can mean two different things, and mixing them up causes bugs. One is putting an object's keys in alphabetical order, which is about consistency. The other is reordering the items of an array by the value of a field, which is about the meaning of the data. This guide covers both, with the pitfalls that catch people out.

Two different operations

Sort object keysSort array items
What changesThe order of keys inside each objectThe order of elements in an array
Changes the meaning?No. JSON objects are unorderedYes. Arrays are ordered, so order can matter
Typical goalStable output, clean diffs, easier readingShow the newest first, group by name, rank by score
Tooljq -S, sort_keys=Truesort_by, .sort(), sorted()

Sort the keys of an object

Programs often write keys in whatever order they were created, so two runs of the same code can produce files that differ only in key order. Sorting the keys makes the output predictable, which keeps version-control diffs small and makes two files easy to compare.

{ "zip": "411001", "name": "Asha", "city": "Pune" }
Before
{ "city": "Pune", "name": "Asha", "zip": "411001" }
After sorting keys alphabetically
jq -S . data.json                 # sorts keys at every level
python -c "import json,sys; print(json.dumps(json.load(sys.stdin), indent=2, sort_keys=True))" < data.json
// JSON.stringify has no built-in key sorting, so sort recursively
function sortKeys(value) {
  if (Array.isArray(value)) return value.map(sortKeys);
  if (value && typeof value === "object") {
    return Object.fromEntries(
      Object.keys(value).sort().map((key) => [key, sortKeys(value[key])])
    );
  }
  return value;
}

console.log(JSON.stringify(sortKeys(data), null, 2));
Arrays keep their order; only object keys are sorted

A JavaScript detail

JavaScript puts integer-like keys such as "10" and "2" first in ascending numeric order, ahead of other keys, whatever order you insert them in. So an object with keys like that cannot be fully alphabetized when represented as a JavaScript object.

Sort an array of objects by a field

Take a list of people:

[
  { "first": "Rohan", "last": "Mehta", "age": 41 },
  { "first": "Asha",  "last": "Rao",   "age": 29 },
  { "first": "Meera", "last": "Mehta", "age": 35 }
]
jq 'sort_by(.age)' people.json                 # youngest first
jq 'sort_by(.age) | reverse' people.json       # oldest first
jq 'sort_by(.last, .first)' people.json        # by last name, then first name
const byAge = [...people].sort((a, b) => a.age - b.age);

// Text fields: localeCompare handles accents and case sensibly
const byName = [...people].sort(
  (a, b) => a.last.localeCompare(b.last) || a.first.localeCompare(b.first)
);
Copy the array first with [...people] if you do not want to modify the original
by_age = sorted(people, key=lambda p: p["age"], reverse=True)
by_name = sorted(people, key=lambda p: (p["last"], p["first"]))

Both JavaScript's Array.prototype.sort (since ES2019) and Python's sorted are stable: items that compare equal keep their original relative order. That is what makes multi-step sorting reliable. To sort by last name and then by age, you can sort by age first and then by last name.

Pitfalls to watch for

  • Numbers stored as strings sort as text. "10" comes before "9", because "1" is less than "9". Convert to numbers before comparing, or use localeCompare with the numeric: true option.
  • Mixed types. Comparing a number with a string, or null with either, gives inconsistent results in some languages and an error in Python 3. Normalize the field first.
  • Missing fields. Decide whether items without the field go first or last, and write the comparison for it explicitly.
  • Case and accents. A plain string comparison puts all capital letters before lowercase ones, so "Zoe" comes before "adam". Use a locale-aware comparison for names.
  • Dates. ISO 8601 strings in the same format and time zone sort correctly as plain text. Strings in other formats, such as 12/10/2026, do not. Parse them first.
  • Order-sensitive arrays. Never sort an array whose order carries meaning, such as steps in a workflow, coordinates of a polygon or a priority list.

Canonical JSON for hashing and signing

If you need the exact same bytes for the same data, for example to compute a hash or a signature, key sorting is part of the answer but not all of it. Whitespace, number formatting and string escaping can also differ between libraries. RFC 8785, the JSON Canonicalization Scheme (JCS), defines a precise, deterministic form for this purpose, and libraries implement it for most languages.

A practical routine for comparing files

  1. Format both files the same way.
  2. Sort the object keys in both.
  3. Leave arrays alone unless you know their order does not matter.
  4. Then compare them with a text diff or a structural tool.

That sequence removes the noise that does not matter and leaves the real differences. See our guide to comparing two JSON files for more.

Frequently asked questions

Does the order of keys in JSON matter?

Not according to the specification: an object is an unordered collection. Some programs do rely on the order they read, so do not assume every consumer ignores it, but you should never depend on it for meaning.

Can I sort by a nested field?

Yes. In jq use sort_by(.address.city), in JavaScript compare a.address.city with b.address.city, and in Python use a key function such as lambda p: p["address"]["city"].

How do I sort in descending order?

In jq pipe the result through reverse. In JavaScript swap the operands (b.age - a.age). In Python pass reverse=True.

Why does my sorted file look different after I save it in another tool?

Some tools rebuild objects from internal data structures that do not keep your order, or sort keys on save. If key order matters for your workflow, check that every tool in the chain preserves it.

Related guides

See all 12 guides

© 2026 TrueJson. All rights reserved.