Sort JSON by values

How sorting JSON by value works, what it changes in the stored text, where the new order can be lost, and when a different structure is the better choice.

Short verdict

Sorting JSON by value is useful when a person needs to scan data, such as finding the largest counts, the cheapest items or the latest dates. The main tradeoff is that JSON objects are defined as unordered, so many parsers, databases and languages are not required to keep the order you produce. If a program depends on the order, put the data in an array instead of relying on a sorted object. Leave the original file unsorted when it is under version control, signed or hashed, or read by tools that compare files byte for byte. In those cases a sorted copy is usually the safer choice.

What "sort by value" can mean

The phrase covers several different operations, and many tools offer only one of them. Check which one you need before you choose a tool or command. In this context, "reverse" normally means descending order. It does not mean reversing the characters inside strings, and sorting does not mirror or restyle any text.

Operation | Input shape | What gets reordered | Typical use
Sort object members by value | {"a": 3, "b": 1} | Key/value pairs, ranked by their values | Ranking counts or scores in a lookup object
Sort an array of objects by a field | [{"name": "x", "price": 5}, ...] | Array elements, ranked by one property | Tables, listings, API results
Sort an array of primitives | [3, 1, 2] or ["b", "a"] | Array elements | Simple lists
Sort by key (often confused with the above) | {"b": 1, "a": 3} | Members, alphabetised by key name | Stable diffs, canonical output

What the transformation actually changes

Sorting rearranges members or elements in the stored JSON text. It is a real change to the characters in the file, not a display effect. The values themselves should not change. In practice, though, most tools parse the input and serialize it again, and that step can change things that have nothing to do with order. Whitespace, indentation, escape sequences and number formatting may all come out differently. Byte-level differences can therefore appear even in members that did not move.

In the example below, an object is sorted in ascending order by numeric value. The output follows the expected mechanism: 3, then 7, then 12. Every key keeps its original value.

Input:
{"banana": 3, "apple": 12, "cherry": 7}

Output (ascending by value):
{
  "banana": 3,
  "cherry": 7,
  "apple": 12
}

Common ways to do it

These snippets use documented behavior of each language or tool. They have not been benchmarked or tested against any particular dataset for this review.

# jq: sort an object's members by value (ascending)
jq 'to_entries | sort_by(.value) | from_entries' input.json

# jq: descending
jq 'to_entries | sort_by(.value) | reverse | from_entries' input.json

# jq: sort an array of objects by a field
jq 'sort_by(.price)' input.json
# Python 3.7+ (dicts keep insertion order)
import json

with open("input.json") as f:
    data = json.load(f)

sorted_data = dict(sorted(data.items(), key=lambda kv: kv[1]))
print(json.dumps(sorted_data, indent=2, ensure_ascii=False))
// JavaScript: numeric values
const sorted = Object.fromEntries(
  Object.entries(data).sort(([, a], [, b]) => a - b)
);

// JavaScript: string values, locale-aware
const byName = Object.fromEntries(
  Object.entries(data).sort(([, a], [, b]) => a.localeCompare(b))
);

Comparison pitfalls that change the result

  • Numbers stored as strings sort as text, so "10" comes before "9". Convert them first if they represent quantities.
  • Mixed value types behave differently in each tool. jq has a defined cross-type order (null, false, true, numbers, strings, arrays, objects). Python 3 raises a TypeError when it compares a string with a number. JavaScript's default sort, called without a comparator, converts values to strings.
  • Nested objects or arrays as values have no obvious order. Decide which inner field to sort on, or exclude those members.
  • Ties keep their original relative order only if the sort is stable. Python's sorted and JavaScript's Array.prototype.sort (since ES2019) are documented as stable. Confirm this for any other tool you use.
  • String order depends on the comparison rule. Code-point comparison puts all uppercase letters before lowercase ones, while locale-aware collation does not.
  • Accented text can be stored either as a precomposed character or as a base letter plus a combining mark. The two look identical but compare differently by code point. Normalize the strings (for example to NFC) before sorting if the input may mix both forms.

Will the order survive copying or sharing?

Copying and pasting JSON text keeps the order, because the result is ordinary characters with no styling or special symbols. The risk comes later, when another program parses the data. The JSON specification (RFC 8259) describes an object as an unordered collection, and any implementation may ignore or change member order. Some documented examples follow.

  • JavaScript objects always list integer-like keys (such as "1" or "42") first, in ascending numeric order, before other string keys. A value-sorted object with numeric-looking keys can therefore be reordered as soon as it is parsed in a browser or Node.js.
  • PostgreSQL's jsonb type does not preserve the order of object keys. Its plain json type stores the original text.
  • Formatters and serializers with a "sort keys" option will undo a value sort. JSON canonicalization schemes such as RFC 8785 do the same, because they order members by key.
  • If the order matters to whoever receives the data, send an array of entries, for example [{"key": "banana", "value": 3}, ...]. Arrays are ordered by definition, so the ranking survives any compliant parser.

Readability, editing and review

A value-sorted file is easier to scan for extremes. It is usually harder to find a specific key in, and harder to compare across versions. When the values change, members move, so a version-control diff can show many moved lines even though only a few numbers changed. Sorted copies often work better as generated reports than as the files people edit and review.

Accessibility concerns are limited compared with styled or mirrored text, because sorting introduces no substitute characters or visual tricks. A screen reader reads the output in the same way it reads the input. How a particular screen reader announces braces, quotes and punctuation depends on its settings, and that was not tested for this review.

Side effects to check before trusting the output

  • Duplicate keys: converting to a dictionary or using from_entries keeps only one value per key, so any duplicates in the input are silently lost.
  • Large integers: JavaScript numbers lose precision above 2^53 - 1, so IDs or counters beyond that limit can change during a parse-and-serialize cycle.
  • Number formatting: values such as 1.0 or 1e3 may be written back in a different form even though they have the same numeric value.
  • Escaping: non-ASCII characters may be escaped or unescaped depending on serializer settings. Python's ensure_ascii option is one example.
  • Signatures and hashes: any reordering changes the bytes, so a signature or checksum computed over the original will no longer match.

Using an online JSON sorter

No specific online tool was evaluated for this review. A tool's appearance or its claims about client-side processing are not evidence of how it handles your data. Read its stated privacy terms, and do not paste credentials, personal data or proprietary payloads unless you can confirm how the input is processed. Whichever tool you use, parse the output again and compare the number of members and the values with the original, so you know nothing was dropped or altered.

When to keep the original order

Keep the original, unsorted JSON when it is a source of truth, under version control, signed, or consumed by software that expects a fixed layout. Do the same when the values are mixed types or nested structures that have no meaningful ranking. In these cases, sort a copy for human reading, or convert the object to an array of entries if the order itself needs to be part of the data.

Gaps in this review

No subject-specific evidence was available. That means no tool comparisons, performance figures or test results against named applications or assistive technologies. The statements above rely on published specifications and documented language behavior. Check the behavior of your own parser, database or destination before you depend on a sorted order.