Blog
Wild & Free Tools

Sort JSON Keys in JavaScript — The JSON.stringify Replacer Pattern and When to Skip It

Last updated: February 2026 6 min read
Quick Answer

Table of Contents

  1. Replacer pattern
  2. Recursive helper
  3. Library option
  4. TypeScript
  5. When to skip code
  6. Frequently Asked Questions

JavaScript does not have a sort_keys=True flag like Python. To sort JSON keys alphabetically in JS, you use JSON.stringify with a replacer function, a recursive helper, or a library like sort-keys. All three work. For a one-time sort of a JSON blob sitting in your clipboard, none of them are necessary — the JSON Key Sorter is faster.

This post walks through the three JS patterns, when to use each, and when to skip code entirely.

Pattern 1 — JSON.stringify Replacer

JSON.stringify accepts a replacer argument. The trick: pass an array of all keys in sorted order. The serializer emits keys in that array's order.

function sortKeys(obj) {
  const allKeys = new Set();
  JSON.stringify(obj, (k, v) => (allKeys.add(k), v));
  const sorted = Array.from(allKeys).sort();
  return JSON.stringify(obj, sorted, 2);
}

This is a common Stack Overflow snippet. It works, but has gotchas: the replacer array applies globally, so nested objects with keys named the same as parent keys can produce weird output. It is also not the most readable pattern.

Use this when you need a one-liner that does not pull in a dependency and the JSON is simple (no key collisions across levels).

Pattern 2 — Recursive Helper Function

The more robust approach builds a sorted clone recursively:

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(originalObj);
console.log(JSON.stringify(sorted, null, 2));

This is what our browser tool does internally. It is 7 lines, handles nesting and arrays correctly, and has no edge cases around name collisions.

Use this for production code where you want clear, predictable behavior.

Sell Custom Apparel — We Handle Printing & Free Shipping

Pattern 3 — sort-keys or json-stable-stringify

Two popular npm packages:

sort-keys (by sindresorhus) — npm install sort-keys. One function: sortKeys(obj, {deep: true}). Deep sorts nested. Tiny package.

json-stable-stringifynpm install json-stable-stringify. Wraps JSON.stringify with stable key ordering (alphabetical by default, customizable). Used for canonical hashing.

Both are battle-tested. Use one when you need canonical JSON output for hashing, signing, or deterministic comparisons — this is a real need in crypto, audit logs, and reproducible builds.

Do not install these for one-off sorting. The 7-line recursive helper above does the same job without the dependency.

TypeScript Notes

Sorting keys does not affect type information — a sorted User is still a User. No type changes needed.

If you want the sort helper to be type-safe, a simple generic signature works:

function sortKeys<T>(obj: T): T {
  if (Array.isArray(obj)) return obj.map(sortKeys) as unknown as T;
  if (obj === null || typeof obj !== 'object') return obj;
  const sorted: Record<string, unknown> = {};
  Object.keys(obj).sort().forEach(k => {
    sorted[k] = sortKeys((obj as Record<string, unknown>)[k]);
  });
  return sorted as T;
}

The any casting is unavoidable for recursion over untyped object trees. For strictly typed JSON with a known schema, use Zod or io-ts to validate first, then sort — see our JSON to Zod schema generator for generating those validators automatically.

When to Skip Code Entirely

You are looking at a JSON response in browser DevTools and want it alphabetized to find a field. Paste into the browser tool, 5 seconds.

Someone sent you a JSON config to review. Sort it, scan it, done. No need to fire up Node.

You want to diff two API responses. Sort both, paste to diff checker.

You want to commit sorted JSON to a repo. For a one-time cleanup, browser works. For ongoing enforcement, set up Prettier + sort plugin so every save alphabetizes.

The pattern: code for repeat automation, browser for single-run tasks.

Sort JSON Without Writing JavaScript

Free browser tool — paste, click, copy. No npm, no helpers.

Open Free JSON Key Sorter

Frequently Asked Questions

Does JSON.stringify sort keys by default?

No. JSON.stringify preserves the order keys were defined in the object. To sort, you either pass a sorted array as the second argument (replacer), or pre-sort the object yourself before stringifying.

Is the replacer array approach reliable?

Mostly, but has edge cases. If a parent and child object share a key name, the global replacer applies the same position for both. For complex nested JSON, the recursive helper function is more predictable.

How does this work in Node.js?

Identical to browser JavaScript. Same JSON.stringify API, same recursive patterns. For CLI tools that sort JSON files, wrap the helper in a small script: read file, parse, sort, write back.

Can I sort keys and keep array element order?

Yes — key sorting only affects objects. Arrays maintain their element order regardless of key sorting. Our browser tool and the recursive helper above both do this correctly.

Jake Morrison
Jake Morrison Security & Systems Engineer

Jake's conviction that files should never touch a third-party server is the foundation of WildandFree's zero-upload design.

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