Blog
Wild & Free Tools

Sort JSON Recursively — How to Alphabetize Deeply Nested Objects

Last updated: March 2026 6 min read
Quick Answer

Table of Contents

  1. Shallow vs deep
  2. Use cases
  3. Browser tool
  4. Python code
  5. JavaScript code
  6. jq command
  7. Frequently Asked Questions

Sorting JSON keys is simple at one level. It gets interesting when the JSON has three, five, or ten levels of nested objects. Recursive sorting walks the entire tree and alphabetizes every object at every depth. Our JSON Key Sorter does this by default — paste, click, done.

This post covers what recursive sorting is, when you need it versus shallow sorting, and the code patterns for doing it in Python, JavaScript, and jq when you want to bake it into an automated pipeline.

Shallow Sort vs Deep (Recursive) Sort

Shallow sort alphabetizes only the top-level keys. Nested objects keep their original internal order.

Deep/recursive sort alphabetizes the top level AND every nested object, at every depth.

Example input:

{
  "zebra": 1,
  "alpha": {
    "mango": "fruit",
    "apple": "fruit",
    "nested": { "kiwi": 5, "banana": 10 }
  }
}

Shallow result:

{
  "alpha": {
    "mango": "fruit",
    "apple": "fruit",
    "nested": { "kiwi": 5, "banana": 10 }
  },
  "zebra": 1
}

Deep result:

{
  "alpha": {
    "apple": "fruit",
    "mango": "fruit",
    "nested": { "banana": 10, "kiwi": 5 }
  },
  "zebra": 1
}

Deep sort is almost always what you want. Shallow is only useful when nested objects have conventional key order that you want to preserve (rare).

When Recursive Sort Matters

Canonical form for hashing. If you hash JSON for integrity checks, the hash must be byte-stable across runs. Deep sort produces a canonical byte sequence regardless of how the object was built — exactly what a hash function needs.

Diffing complex configs. A Kubernetes manifest or Terraform plan can be 500 lines deep. Without recursive sort, meaningless "moved" lines drown out real changes. Recursive sort + diff shows only true differences.

Normalizing API responses. Two microservices return the same data, but with keys in different orders because their serializers differ. Recursive sort normalizes both, so downstream consumers see identical structure.

Reviewing deeply nested test fixtures. Large JSON test fixtures are hard to read. Alphabetizing at every level makes them scannable.

Migrating between systems. When moving JSON between databases, message queues, or file stores, deep-sorting first means the target has a predictable shape to validate against.

Using the Browser Tool for Recursive Sort

Our JSON Key Sorter has recursive mode on by default. The "Sort nested objects recursively" checkbox is checked the first time you open the tool.

What happens under the hood: the tool walks the JSON tree. For every object it finds, it sorts its keys alphabetically (or reverse-alphabetically if you picked Z-A). For arrays, it recurses into each element but does not reorder the array itself. The result preserves arrays and types exactly while producing a fully sorted object hierarchy.

No depth limit for typical payloads. Stack depth in modern browsers handles hundreds of levels of nesting — more than any real JSON payload ever needs. If you somehow have pathologically deep JSON (thousands of levels), browser stack limits may hit. That is a code-generated edge case, not something normal API responses produce.

Sell Custom Apparel — We Handle Printing & Free Shipping

Recursive Sort in Python

Python's built-in json.dumps with sort_keys=True is already recursive:

import json
sorted_output = json.dumps(data, sort_keys=True, indent=2)

If you need the sorted object as a dict (not a string), write a recursive helper:

def sort_nested(obj):
    if isinstance(obj, dict):
        return {k: sort_nested(v) for k, v in sorted(obj.items())}
    if isinstance(obj, list):
        return [sort_nested(i) for i in obj]
    return obj

sorted_data = sort_nested(data)

Both approaches walk the entire tree. For most production use, json.dumps with sort_keys is enough — the string output is what you save, send, or hash.

Recursive Sort in JavaScript

The direct recursive pattern:

function sortObject(obj) {
  if (Array.isArray(obj)) return obj.map(sortObject);
  if (obj === null || typeof obj !== 'object') return obj;
  return Object.keys(obj).sort().reduce((acc, key) => {
    acc[key] = sortObject(obj[key]);
    return acc;
  }, {});
}

const sorted = sortObject(original);
console.log(JSON.stringify(sorted, null, 2));

Seven lines, handles any depth, preserves arrays. For production JS code that needs canonical output for hashing or signing, this is the standard pattern.

For TypeScript and type-safe variants, see our JavaScript sort guide.

Recursive Sort With jq

jq has a flag for this:

jq --sort-keys . input.json

The --sort-keys flag makes jq emit every object with keys in sorted order, recursively. No custom filter needed.

For piping from a command output:

curl -s https://api.example.com/data | jq --sort-keys .

jq is great when JSON is already on the command line. For JSON sitting in a browser tab or email, copying to a file first just to run jq is more friction than paste-and-click.

See also: Format JSON on Linux Without jq — the same principle applies to sorting.

Recursively Sort Your JSON

Deep sort by default. One click, any depth. Free, no upload.

Open Free JSON Key Sorter

Frequently Asked Questions

Is recursive sorting the same as deep sorting?

Yes — the terms are interchangeable. Both mean sorting keys at every nesting level, not just the top. Our tool calls it "recursive" because that describes how the algorithm works; the effect is deep sorting.

Does json.dumps sort_keys sort nested dicts?

Yes. Python json.dumps with sort_keys=True recursively sorts every level. This is different from dict(sorted(obj.items())) which only sorts the top level.

What happens with arrays of objects?

The array order stays as you provided it. Keys inside each array element get sorted. If your array is [{"z":1,"a":2},{"z":3,"a":4}], the output is [{"a":2,"z":1},{"a":4,"z":3}] — elements in original order, keys within each sorted.

How deep can recursion go?

No practical limit for real-world JSON. The browser call stack handles hundreds of levels of nesting. Pathological depth (thousands of levels) may hit stack limits, but typical API payloads are 3-10 levels deep.

Andrew Walsh
Andrew Walsh Developer Tools & API Writer

Andrew worked as a developer advocate at two SaaS startups writing API documentation used by thousands of engineers.

More articles by Andrew →
Launch Your Own Clothing Brand — No Inventory, No Risk