JSON Sorter

Sort JSON object keys alphabetically in ascending or descending order. Recursively format nested objects and arrays for clean diff comparisons, Git version control, and consistent data structures.

How to Sort JSON Keys Online

1

Input JSON

Paste raw JSON payload on the left, click Upload to load a file, or click Sample.

2

Configure Options

Select sort order (A-Z or Z-A), indentation spacing (2/4 spaces, tabs, or minify), and sorting depth (Deep or Shallow).

3

Export Sorted JSON

Keys sort automatically in real time. Click Copy or Download to save the sorted document.

Tool Options

Alphabetical Sorting (A-Z & Z-A)

Reorders object keys alphabetically in ascending or descending order using standard locale-aware collation.

Deep Recursive Sorting

Recursively traverses nested objects and arrays to ensure every internal key is consistently ordered across all levels.

Deterministic Git Diffs

Canonical key ordering eliminates arbitrary key position changes across API responses and version control commits.

Your Data Privacy

Web Tool
Privacy-First Architecture
Most of our web tools process your data entirely in-browser. Where server processing is technically required, payloads are evaluated statelessly in-memory and are never stored, saved, or logged.
REST API
Stateless In-Memory Processing
When you use our API endpoints, your requests are processed strictly in-memory without persistent database storage, disk logging, or data retention.
Want to learn more about how we safeguard your information and infrastructure?
Read our full Privacy Policy for detailed security standards, data retention principles, and compliance guarantees.

What does the JSON Sorter do?

The JSON Sorter reorders JSON object keys alphabetically in ascending (A-Z) or descending (Z-A) order in real time. Executing 100% in-browser on blueutils.com, it recursively traverses deeply nested objects, arrays, and dictionaries to produce deterministic, canonical JSON structures. Sorting keys eliminates arbitrary key reordering across serialization runtimes, making Git diffs clean, code reviews readable, and API response caching reliable.

  • Real-Time Zero-Latency Key Sorting: Reorders JSON object keys as you type with instant syntax validation and error gutter location.
  • Deep Recursive vs. Shallow Traversal: Recursively sorts nested keys across multidimensional hierarchies or sorts only the root object properties.
  • Array Preservation: Preserves ordered sequential array elements by default while cleanly sorting objects nested inside array lists.

Core Concepts & Technical Specifications

  1. Canonical Ordering & Deterministic Hashing:
    • Standard JSON specifications define objects as unordered collections of key-value pairs. Normalizing key order alphabetically ensures deterministic payload hashing (e.g. JWT tokens, HMAC signatures) and consistent JSON snapshot comparisons.
  2. Deep Recursive Traversal:
    • Traverses nested object hierarchies down to primitive leaves, sorting object keys at every level while leaving sequential array indices intact.
  3. In-Browser Privacy:
    • All sorting and formatting algorithms execute locally in browser memory.
    • No data is transmitted to external servers, logged, or retained.

How to use the tool?

  1. Input JSON Data:
    • Paste your raw JSON payload into the left editor, click Upload to load a local .json file, or click Sample.
  2. Configure Options:
    • Select your sort order (A-Z (Asc) or Z-A (Desc)), indentation spacing (2 Spaces, 4 Spaces, Tabs, or Minify), and depth (Deep Recursive or Shallow (Root)).
  3. Copy or Download:
    • Sorted JSON appears instantly in the right editor. Click Copy to copy to your clipboard or Download to save as output.json.

Pipeline & Contextual Workflows

  • Deterministic Git Diffs: Sort schema files and mock datasets before committing to eliminate noisy line changes caused by arbitrary key serialization.
  • JSON Formatting & Minification: Format or compress sorted JSON payloads with JSON Formatter & Beautifier or JSON Minifier.
  • Structural Diffing: Inspect sorted payloads side-by-side using JSON Diff Tool.

REST API Integration

blueutils.com provides a free REST API endpoint (POST https://blueutils.com/api/json/sorter or POST https://blueutils.com/api/json/sort) for automated CI/CD config generation, Git pre-commit hooks, and data pipelines.

API Request Parameters

Name Type Description Example
rawText / json String / Object Raw JSON string or JSON object payload to sort. "{\"zebra\":\"animal\",\"apple\":\"fruit\"}"
order String Sort order: "asc" (default) or "desc". "asc"
recursive Boolean Recursively sort nested sub-objects (default: true). true
indent Number / String Indentation spaces (e.g. 2, 4, or "tab"). Defaults to 2. 2
sortArrays Boolean Optionally sort primitive array elements (default: false). false

API Request Payload Examples

cURL (Using Direct JSON Object)

curl -X POST https://blueutils.com/api/json/sorter \
  -H "Content-Type: application/json" \
  -d '{
    "json": {
      "zebra": "animal",
      "apple": "fruit",
      "banana": "fruit"
    },
    "order": "asc",
    "recursive": true,
    "indent": 2
  }'

Python

import requests

url = "https://blueutils.com/api/json/sorter"
payload = {
    "json": {
        "zebra": "animal",
        "apple": "fruit",
        "banana": "fruit"
    },
    "order": "asc",
    "recursive": True,
    "indent": 2
}
headers = {"Content-Type": "application/json"}
response = requests.post(url, json=payload, headers=headers)
print(response.json())

Java

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {
    public static void main(String[] args) throws Exception {
        String jsonPayload = """
            {
                "json": {
                    "zebra": "animal",
                    "apple": "fruit"
                },
                "order": "asc",
                "recursive": true,
                "indent": 2
            }
            """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://blueutils.com/api/json/sorter"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
            .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

API Response Parameters

Name Type Description Example
isValid Boolean Indicates whether the sort operation succeeded. true
result String Sorted and formatted JSON string output. "{\n \"apple\": \"fruit\",\n \"zebra\": \"animal\"\n}"
data Object / Array Parsed JavaScript object/array representation with sorted keys. {"apple":"fruit","zebra":"animal"}
originalSize Number Byte size of raw input payload in UTF-8. 45
resultSize Number Byte size of sorted output JSON in UTF-8. 52
keysSortedCount Number Total number of object keys processed across all levels. 2
error String Detailed error explanation returned on invalid syntax. "Invalid JSON syntax: Unexpected token '}' (Line 2)"

API Response Payload Examples

Success Response (HTTP 200 OK)

{
  "isValid": true,
  "message": "JSON keys sorted in ascending order successfully.",
  "result": "{\n  \"apple\": \"fruit\",\n  \"banana\": \"fruit\",\n  \"zebra\": \"animal\"\n}",
  "data": {
    "apple": "fruit",
    "banana": "fruit",
    "zebra": "animal"
  },
  "order": "asc",
  "recursive": true,
  "originalSize": 45,
  "resultSize": 52,
  "nodeCount": 3,
  "keysSortedCount": 3
}

Validation Failure Response (HTTP 400 Bad Request)

{
  "isValid": false,
  "error": "Invalid JSON syntax: Unexpected token '}' at position 15 (Line 1, Column 16)"
}

Rate Limit Exceeded Response (HTTP 429 Too Many Requests)

{
  "error": "API rate limit exceeded. Please wait or contact support@blueutils.com."
}

Why use an API to sort JSON?

Automating JSON key sorting improves version control stability:

  • Clean Git Diffs: Eliminates noisy line changes in CI/CD configuration files caused by unordered serialization.
  • Deterministic Token Hashing: Ensures identical payload hashes when verifying digital signatures, JWTs, or cache keys.
  • LLM Context Optimization: Normalizes object structures before feeding them into prompt contexts for faster parsing.

Native Usage

Sort JSON keys locally across terminal environments and programming runtimes:

Linux / macOS (jq)

# Sort all keys alphabetically in JSON using jq
jq -S . input.json > output.json

Windows (PowerShell)

# Read JSON, sort properties recursively, and write formatted output
$json = Get-Content -Raw -Path .\input.json | ConvertFrom-Json

function Sort-JsonObject {
    param($InputObject)
    if ($InputObject -is [System.Management.Automation.PSCustomObject]) {
        $sorted = [ordered]@{}
        $InputObject.PSObject.Properties.Name | Sort-Object | ForEach-Object {
            $sorted[$_] = Sort-JsonObject $InputObject.$_
        }
        return [PSCustomObject]$sorted
    } elseif ($InputObject -is [System.Collections.IList]) {
        return @($InputObject | ForEach-Object { Sort-JsonObject $_ })
    }
    return $InputObject
}

(Sort-JsonObject $json) | ConvertTo-Json -Depth 10 | Set-Content .\output.json

Python

import json

raw_json = '{"zebra": "animal", "banana": "fruit", "apple": "fruit"}'
parsed = json.loads(raw_json)
print(json.dumps(parsed, sort_keys=True, indent=2))

Java (Jackson / TreeMap)

import java.util.Map;
import java.util.TreeMap;

public class Main {
    public static Map<String, Object> sortMapRecursively(Map<String, Object> map) {
        Map<String, Object> sorted = new TreeMap<>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getValue() instanceof Map) {
                sorted.put(entry.getKey(), sortMapRecursively((Map<String, Object>) entry.getValue()));
            } else {
                sorted.put(entry.getKey(), entry.getValue());
            }
        }
        return sorted;
    }
}

Frequently Asked Questions (FAQ)

Why should I sort JSON object keys alphabetically?

Sorting JSON keys produces canonical, deterministic structures. This eliminates noisy Git commit diffs caused by arbitrary key reordering, simplifies code reviews, and ensures consistent snapshots for testing.

Does sorting JSON keys affect the order of items inside arrays?

No. By default, array element ordering is preserved because JSON arrays represent ordered lists. However, objects nested inside arrays are recursively sorted.

How do I sort JSON keys in the command line using jq or Python?

Using jq, run jq -S . input.json > output.json. Using Python, run python -m json.tool --sort-keys input.json output.json.

How do I sort JSON keys in Visual Studio Code?

In VS Code, press Ctrl + Shift + P (or Cmd + Shift + P on macOS), search for Sort JSON (using the Sort JSON extension), or use Prettier formatting.

Is my JSON data kept private when using this online JSON Sorter?

Yes. All key sorting and formatting operations execute 100% client-side directly in your browser. Your JSON payloads never leave your computer.

Rate Limits

UI Limits
100 uses per 15 minutes
Max payload size: 5 MB
API Limits
5 requests per 60 minutes
Max payload size: 256 KB
Need higher API rate limits, increased payload sizes, or custom developer solutions?
Contact our engineering team at support@blueutils.com for custom rate limit increases, higher quota allocations, or tailored enterprise integrations.