JSON Sort
Free online JSON Sort tool. One-click arrange object keys alphabetically or sort array elements by value. Toggle ascending/descending and recursion into nested structures.
Related
What is JSON Sort?
JSON Sort is the reordering of keys inside a JSON object by some order (most commonly alphabetical), or the reordering of elements in a JSON array by some rule (numeric value, lexicographic order). It does not change any field value or type, only the physical order — a typical canonicalization operation that aligns JSON from different sources, times, and authors into a single structural shape.
The 5 main reasons JSON sort is needed in practice: ① **Reduce Git Diff noise** — different developers construct JSON objects in different orders, generating huge meaningless diffs on commit. After unifying key order, the diff focuses on real changes. ② **Config normalization** — CI/CD pipelines, config centers, and Feature Flag services want all environments' configs to have consistent key order for easier audit, rollback, and cross-environment diff. ③ **Data comparison** — pre-sorting before using a JSON Diff tool eliminates false differences caused by different key orders. ④ **API response standardization** — frontends caching or hashing responses want stable key order, to avoid treating the same business data as different keys due to different orderings. ⑤ **Readability** — hand-written JSON is often built field-by-field by business logic; sorting makes it visually tidier.
At the implementation level, the core of JSON sort is sorting each level of object keys with `localeCompare`, and processing nested objects recursively. GeekFormat's JSON Sort tool has two modes: ① **Sort by key** (default) — only reorders object keys alphabetically, preserving array element order. ② **Sort by array element** — sorts array elements by their serialized-string lexicographic order. It also supports a recursive toggle and ascending/descending switch. The whole process happens locally in the browser; nothing is uploaded.
Use Cases
- Unify key order in team JSON config files, package.json, tsconfig.json, etc. to reduce Git Diff noise
- Sort two JSONs before comparing to eliminate false differences from different key orders, letting diff focus on real changes
- Standardize API response data key order to ease front-end caching, IndexedDB storage, and object hash computation
- Persist CI/CD config center, Feature Flag service configs in canonical key order, for easier audit and rollback
- Tidy large JSON config files or data exports — sorting keys alphabetically makes them visually cleaner
- Unify key order before writing JSON to database / Redis / message queue, to guarantee idempotent downstream consumption
How to Use
- Paste the JSON content to be sorted into the left input box, or click "Sample" to load a typical multi-level JSON, or upload a .json/.txt file
- Select sort mode from the bottom options bar: default "Sort by key"; switch to "Sort by array" if you need to sort array elements
- Toggle the ascending / descending button as needed, check or uncheck "Recursive" (on by default)
- Click the "Sort" button; the right output box shows the formatted sorted result. Click "Copy" or "Download" to save as sorted.json
Features
- Two sort modes: supports "Sort by object key" and "Sort by array element" core modes, switchable with one click
- Recursive nested processing: recursion on by default, descending into multi-level nested objects to sort keys at every level, ensuring structure is consistently tidy
- Ascending/Descending toggle: built-in ascending (A-Z) / descending (Z-A) toggle button, flexible for reading habits and business requirements
- localeCompare dictionary order: key comparison uses local dictionary order, correctly sorting Chinese, special characters, and emoji
- Preserves data structure: only adjusts key name and array element order, does not add or remove fields, does not modify value types
- Sample data quick experience: built-in "zoo + alpha/beta/omega" demo data, one-click load to see the sort effect
- Local processing for privacy: parsing, sorting, and formatting all happen locally in the browser, no input sent to any server
- Seamless downstream handoff: sorted results can be one-click copied to JSON Formatter, Diff Compare, Schema Validator, etc. for further processing
Code Examples
JavaScript object key sort with Object.keys + sort
javascript// Recursive key sort, returns a new object (does not modify original)
function sortKeysDeep(value) {
if (Array.isArray(value)) return value.map(sortKeysDeep);
if (value !== null && typeof value === 'object') {
return Object.keys(value)
.sort((a, b) => a.localeCompare(b))
.reduce((acc, k) => {
acc[k] = sortKeysDeep(value[k]);
return acc;
}, {});
}
return value;
}
const data = { zoo: { animals: ['zebra', 'elephant'] }, alpha: 1, beta: 2 };
const sorted = sortKeysDeep(data);
console.log(JSON.stringify(sorted, null, 2));
// => {
// "alpha": 1,
// "beta": 2,
// "zoo": { "animals": ["zebra", "elephant"] }
// }Python sort_keys=True + array sort
pythonimport json
data = {"zoo": {"animals": ["zebra", "elephant"]}, "alpha": 1, "beta": 2}
# Auto-sort by alpha when serializing with sort_keys
sorted_json = json.dumps(data, indent=2, sort_keys=True, ensure_ascii=False)
print(sorted_json)
# Array sort by value
arr = [3, 1, 4, 1, 5, 9, 2, 6]
print(sorted(arr)) # numeric ascending
print(sorted(arr, reverse=True)) # descending
# String dictionary order
print(sorted(['banana', 'Apple', 'cherry'])) # ['Apple', 'banana', 'cherry']Sort by key with jq
bash# Recursive key sort + 2-space indent jq -S '.' data.json # Explanation: -S (--sort-keys) sorts all object keys recursively in ASCII ascending order # Sort array by element string lexicographic order (objects compare by their JSON string) jq 'sort' data.json # Sort array by some field (e.g. by age ascending) jq 'sort_by(.age)' data.json # Descending jq 'sort_by(.age) | reverse' data.json
FAQ
What is the difference between JSON Sort and JSON Formatter?
JSON Formatter only adjusts indentation, line breaks, and whitespace characters, without changing the order of keys. JSON Sort reorders the physical order of key names (alphabetically) or array elements (by value size). The two are often used together: sort first to tidy the structure, then format to make the content readable — the final output is the cleanest JSON.
Will the sorted JSON get larger?
Byte count is essentially unchanged. Sort doesn't add or remove fields, only reorders key names, so the serialized character count is almost the same as the original (indentation characters may differ by 1-2 bytes).
Does it change field values or field types?
No. This tool is a pure structural reorder: object keys are rearranged, array elements are repositioned, values and types remain untouched. Relative semantics of `null`, booleans, numbers, strings, objects, and arrays are all preserved.
Can I sort object keys by value?
This tool currently supports two modes: ① sort by object key alphabetical (the object's key order changes); ② sort array elements by value (elements inside an array change position). If you need to sort array elements by some object field value, please first use the JSON Path tool to extract that field into a top-level array, then use the array mode to sort.
What does recursive sort mean? Should I turn it off?
Recursive = sort key names at every level of nested objects. Non-recursive = only sort the top-level object keys; sub-objects keep their original order. In most scenarios we recommend keeping recursion on for a consistent tidy structure. Only when your inner objects have specific order semantics (e.g. a "priority list" in config) would you turn recursion off.
Why are my integer keys sorted to the front?
This is JavaScript spec behavior: when an object's keys look like non-negative integers (0, 1, 2...), the engine iterates them in numeric ascending order — integer keys appear before string keys. This tool's sort preserves that behavior. If you want "integer-looking keys also sorted in string order", use JSON Repair or an editor to change them to quoted string keys like "0", "1".
Can Chinese key names be sorted by Pinyin?
Yes. Under the hood this tool uses JavaScript's localeCompare, which sorts according to the current browser's locale by default. In a Chinese environment it basically sorts by Pinyin ascending, but the exact behavior varies with browser and OS. For strict Pinyin sorting, use a Node.js library supporting ICU collation rules (e.g. `natural-orderby`).
How to sort objects inside an array?
Array mode supports sorting the objects inside an array by the "lexicographic order of the serialized string" — that means objects are sorted by the string value of the first differing field. To sort by a specific field (e.g. price, date), use a sort-by operation in the JSON Path tool, or in code use `Array.prototype.sort((a, b) => a.price - b.price)`.
Can I undo and restore the original order after sorting?
This tool doesn't maintain an original-order history (for simplicity). Recommendations: ① Copy the original to clipboard before modifying; ② Save the original as a .json file for rollback; ③ Use git to manage originals in production — `git checkout` any historical version when needed.
Can the sorted result be exported and saved?
Yes. Click "Download" to save as sorted.json; or click "Copy" to put the result in the clipboard and paste into code or documents. The downloaded file is standard JSON, consumable by any editor, IDE, or CI tool.
Will the tool upload my JSON to a server?
No. Parsing, sorting, and formatting all happen locally in the browser; input and intermediate results are not sent to any server. Works offline, suitable for handling sensitive JSON (e.g. internal configs, unpublished API responses).
What is the best order of use with JSON Diff and Schema Validation?
Recommended chain: ① JSON Repair (clean illegal JSON) → ② JSON Sort (unify key order) → ③ JSON Diff (compare based on sorted result, minimum diff noise) → ④ JSON Formatter (unify indent for readability) → ⑤ JSON Schema Validation (business field constraints). Pick whichever steps you need.
Troubleshooting
Sort shows "Invalid JSON" error
Cause: input is not valid JSON. Solution: first paste the JSON into the JSON Repair tool to clean (auto-handle trailing commas, single quotes, unquoted keys, etc.), then come back to this tool; or check if you missed outer braces / brackets.
Integer keys sort to the front
Cause: JavaScript spec iterates "non-negative-integer-looking" keys in numeric ascending order. Solution: change integer keys to string keys ("0", "1") before sorting; or accept this behavior as a feature.
Array objects didn't sort by my expected field
Cause: array mode sorts by the lexicographic order of the serialized string, with the first differing field deciding the final order. Solution: use sort-by in the JSON Path tool; or in code use `arr.sort((a, b) => a.field - b.field)` to customize the comparator; this tool mainly targets key-name sorting scenarios.
Chinese key names don't sort as expected
Cause: localeCompare behavior varies slightly across browsers/OS, and for Chinese it defaults to Unicode code points or browser locale. Solution: explicitly specify the locale in code (e.g. `localeCompare('zh-CN')`); or switch to a library supporting ICU collation rules for strict Pinyin sort.
Inner nested objects not sorted (only the outer level was)
Cause: "Recursive" in the bottom options bar is not checked. Solution: check the "Recursive" switch (checked by default), re-trigger sort; inner object keys will also be sorted alphabetically.
Large files (10 MB+) cause sort to freeze
Cause: parsing large text with JSON.parse at once takes a lot of memory. Solution: keep input within 1-2 MB; for huge files use Node.js (`Object.keys(...).sort()`) or Python (`json.dumps(..., sort_keys=True)`) scripts locally; use this tool for small verification afterwards.
Glossary
- JSON Sort
- Reordering JSON object keys alphabetically or array elements by value; does not change any field value or type, only physical order.
- localeCompare
- JavaScript built-in string lexicographic comparison function returning -1/0/1. This tool uses localeCompare to sort keys, correctly handling Chinese, special characters, and emoji.
- ASCII Ascending / Descending
- Sort by character Unicode code points (ASCII table); uppercase A-Z comes before lowercase a-z, digits 0-9 come before letters.
- locale-aware Sort
- Sort that respects language conventions; for Chinese it defaults to Unicode code point or browser locale, which differs from strict Pinyin sort.
- Integer-like Key
- An object key that looks like a non-negative integer (e.g. "0", "1", "2"); JavaScript engines auto-iterate them in numeric ascending order. Spec behavior, cannot be turned off.
- Recursive Sort
- Sorting key names at every level of nested objects. This tool enables it by default; disabling it only sorts the top level.
- Canonical Form
- Normalized form; JSON sort is one way to construct a canonical form, easing diff, cache hashing, and cross-environment consistency.
- Git Diff Noise
- Diff lines in code review produced by formatting differences (not real logic changes); commits with differently-ordered JSON keys generate large amounts of noise diff.
- pre-commit Hook
- Script that runs automatically before a Git commit; many teams invoke `jq -S .` in pre-commit to sort JSON file keys before add, ensuring consistent JSON order in the repo.
- JSON Diff Tool
- A tool (e.g. jsondiffpatch) that compares two JSONs to find differences; recommended to sort both sides first, to eliminate false diff from key order.
JSON Sort Scenarios & Method Reference
| Scenario | Sort by | Recommended impl | Matching tool |
|---|---|---|---|
| Reduce Git Diff noise | Object key alphabetical | jq -S | This tool / jq |
| Config center normalization | Object key alphabetical | jq -S | This tool / jq |
| API response cache key | Object key alphabetical | JSON.stringify(sort_keys=True) | This tool / Python json |
| Paginated API array merge | No sort | concat | JSON Merge tool |
| Sort array by created time | Array element .created_at | jq 'sort_by(.created_at)' | jq sort_by |
| Sort products by price | Array element .price | lodash _.sortBy | JS sort((a,b)=>a.price-b.price) |
JSON Sort vs JSON Diff vs JSON Merge
| Tool | What it solves | Sort dimension | Usually paired with |
|---|---|---|---|
| JSON Sort (this tool) | Unify key/array order | Keys / array elements | JSON Diff, JSON Merge |
| JSON Diff | Compare two JSONs for differences | None (content-based) | Sort (sort first, then diff) |
| JSON Merge | Multi-source merge | Sort by config | Sort (post-merge normalize) |
| JSON Repair | Convert illegal JSON to valid | None | Sort (post-repair archive) |
| JSON Schema Validation | Field constraint validation | None | Can validate sorted output |
Authoritative References
- JSON Compress
- CSV to JSON
- JSON to CSV
- JSON Diff
- JSON Escape / Unescape
- JSON Flatten
- JSON Formatter
- JSON Generator
- JSONPath Query
- JSON Merge
- JSON Repair
- JSON Schema Validator
- JSON Sort
- JSON Stringify
- JSON to HTML Table
- JSON to Java
- JSON to Markdown
- JSON to SQL
- JSON to TOML
- JSON to TypeScript
- XML to JSON
- JSON to XML
- YAML to JSON
- JSON to YAML
- JSON to Python
- JSON to Go
- JSON to Rust
- JSON to Swift
- JSON to C#
- JSON to C++
- JSON to PHP