YAML Sorter Tool

Alphabetically sort YAML object keys recursively or at the root level. Maintain arrays, format indentation, and normalize YAML configs for clean Git diffs.

How to Use the YAML Sorter

1

Input YAML Data

Paste your YAML document into the editor above, upload a .yaml file, or click Sample.

2

Configure Sorting Rules

Select sort order (A-Z or Z-A), depth (Deep Recursive or Shallow), and indentation spacing.

3

Live Sorting & Export

The tool sorts keys in real time as you type or change options. Click Copy or Download to save your sorted YAML.

Tool Options

Recursive Deep Key Sorting

Traverses all nested mappings, dictionaries, and object hierarchies to sort keys at every level alphabetically.

Git Diff Normalization

Eliminates artificial diff noise in Git commits and pull requests caused by randomly ordered configuration properties.

Optional Primitive Array Sorting

Optionally sorts string and numeric elements inside scalar arrays without altering arrays containing complex objects.

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 YAML Sorter do?

The YAML Sorter on blueutils.com alphabetically sorts object keys in YAML documents, Kubernetes manifests, Docker Compose files, and cloud configuration payloads. It supports both deep recursive sorting across all nested mapping hierarchies and shallow root-level sorting, with configurable ascending (A-Z) and descending (Z-A) ordering, customizable indentation, and optional primitive array sorting.

Core Concepts

Understanding YAML sorting mechanisms ensures consistent configuration management:

  • Recursive vs. Shallow Sorting: Deep recursive sorting navigates through every nested mapping, sequence of maps, and dictionary to order keys at all levels. Shallow sorting orders only top-level root properties while preserving the existing order of nested child blocks.
  • Array Preservation: By default, sequence order and list elements are preserved intact to avoid altering indexed arrays. An optional toggle allows sorting scalar primitive elements (e.g. lists of strings or numbers).
  • Git Diff Normalization: Unifying key order across YAML documents eliminates false diffs in pull requests, simplifies code reviews, and prevents merge conflicts.

How to use the tool?

  1. Paste or Upload YAML Payload: Paste your YAML configuration into the left Raw YAML Input editor, click Upload, or click Sample.
  2. Configure Sorting Rules: Choose sort direction (A-Z or Z-A), sorting depth (Deep Recursive or Shallow), indentation spacing (2 or 4 spaces), and optionally check Sort primitive array elements.
  3. Instant Sorting & Export: The sorter arranges YAML keys in real time as you edit or adjust options. Click Copy to copy the sorted YAML or Download to save your formatted blueutils-sorted.yaml file.

Related Developer Utilities

If you work with YAML formatting, normalization, and configuration files, explore these related tools:

  • YAML Formatter: Prettify and format YAML documents with custom indentation rules.
  • YAML Diff Tool: Compare and inspect semantic differences between two YAML files side-by-side.
  • YAML to JSON Converter: Convert YAML configuration files into standardized JSON documents.
  • JSON Sorter: Alphabetically sort object keys in JSON documents recursively.

REST API Integration

blueutils.com provides a free REST API endpoint (POST https://blueutils.com/api/yaml/sort) to programmatically sort and normalize YAML keys.

API Request Parameters

Name Type Description Example
rawText / yaml String / Object / Array Raw YAML sequence or document payload string / object to sort. "server:\n port: 8080\n host: localhost"
order String (Optional) Sort order: "asc" (default) or "desc". "asc"
depth String (Optional) Sorting depth: "recursive" (default) or "shallow". "recursive"
indent Number/String (Optional) Indentation spaces: 2 (default) or 4. 2
sortArrays Boolean (Optional) Whether to sort primitive scalar arrays. Default is false. false

API Request Payload Examples

cURL (Using Raw String)

curl -X POST https://blueutils.com/api/yaml/sort \
  -H "Content-Type: application/json" \
  -d '{
    "rawText": "server:\n  port: 8080\n  host: localhost\n  auth:\n    secret: abc\n    enabled: true",
    "order": "asc",
    "depth": "recursive",
    "indent": 2
  }'

cURL (Using Direct Object)

curl -X POST https://blueutils.com/api/yaml/sort \
  -H "Content-Type: application/json" \
  -d '{
    "yaml": {
      "server": { "port": 8080, "host": "localhost" }
    },
    "order": "asc"
  }'

Python

import requests

url = "https://blueutils.com/api/yaml/sort"
payload = {
    "rawText": "server:\n  port: 8080\n  host: localhost\n  auth:\n    secret: abc\n    enabled: true",
    "order": "asc",
    "depth": "recursive",
    "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 = """
            {
                "rawText": "server:\\n  port: 8080\\n  host: localhost",
                "order": "asc",
                "depth": "recursive"
            }
            """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://blueutils.com/api/yaml/sort"))
            .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 sorting succeeded. true
message String Confirmation message returned when sorting succeeds. "Successfully sorted 4 keys in YAML document."
sortedYaml String Formatted, alphabetically sorted YAML document. "server:\n host: localhost\n port: 8080"
data Object / Array Parsed and sorted native representation of the YAML document. {"server":{"host":"localhost"}}
keyCount Number Total number of mapping keys sorted. 3
originalSize Number Byte size of raw input payload in UTF-8. 42
resultSize Number Byte size of sorted YAML output in UTF-8. 38
error String Summary error description (when isValid is false). "Invalid input: YAML payload cannot be empty."

API Response Payload Examples

Success Response (HTTP 200 OK)

{
  "isValid": true,
  "message": "Successfully sorted 4 keys in YAML document.",
  "sortedYaml": "server:\n  auth:\n    enabled: true\n    secret: abc\n  host: localhost\n  port: 8080",
  "data": {
    "server": {
      "auth": {
        "enabled": true,
        "secret": "abc"
      },
      "host": "localhost",
      "port": 8080
    }
  },
  "keyCount": 4,
  "originalSize": 42,
  "resultSize": 38
}

Validation Failure Response (HTTP 400 Bad Request)

{
  "isValid": false,
  "error": "Invalid input: YAML payload cannot be empty."
}

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 YAML keys?

Integrating the YAML sorting API into pre-commit hooks, automated linting pipelines, and CI workflows provides immediate consistency benefits:

  • Pre-Commit Linting & Git Hygiene: Automatically normalize Kubernetes manifests, Helm charts, and CI configs before merging, preventing unnecessary line changes.
  • Optimized Token Efficiency for AI Agents: AI assistants can normalize and sort large YAML configurations with a single API call instead of generating reshuffled structures token by token.
  • Deterministic Key Ordering: Ensures predictable ordering of fields for machine readability and reproducible automated builds.
  • Deterministic Key Ordering: Ensures predictable object ordering across microservices, multi-cloud templates, and infrastructure-as-code manifests.

Native Usage

How to sort YAML keys locally in terminal environments:

Windows (CMD / PowerShell)

# Sort YAML keys alphabetically using Python in PowerShell
python -c "
import yaml

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

data = yaml.safe_load(open('config.yaml'))
sorted_data = sort_keys(data)
with open('config.sorted.yaml', 'w') as f:
    yaml.dump(sorted_data, f, sort_keys=True)
print('YAML sorted successfully.')
"

Linux / Unix (Bash)

# Sort YAML keys using yq (standard alphabetical sort)
yq -P 'sort_keys(..)' config.yaml > config.sorted.yaml

Python

Using PyYAML:

import yaml

def sort_dict_recursively(data):
    if isinstance(data, dict):
        return {k: sort_dict_recursively(v) for k, v in sorted(data.items())}
    elif isinstance(data, list):
        return [sort_dict_recursively(item) for item in data]
    return data

with open("config.yaml", "r") as f:
    raw_data = yaml.safe_load(f)

sorted_data = sort_dict_recursively(raw_data)
with open("config.sorted.yaml", "w") as f:
    yaml.dump(sorted_data, f, default_flow_style=False, sort_keys=True)

print("YAML keys sorted successfully.")

Java

Using Jackson YAML with SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import java.io.File;

public class YamlSorterExample {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
        mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);

        Object data = mapper.readValue(new File("config.yaml"), Object.class);
        mapper.writeValue(new File("config.sorted.yaml"), data);

        System.out.println("YAML sorted successfully.");
    }
}

Frequently Asked Questions (FAQ)

How do I sort YAML keys alphabetically?

Paste your raw YAML into the input editor, select your preferred sort order (A-Z or Z-A) and depth (Deep Recursive or Shallow), and click Sort YAML Keys. The formatted, alphabetically ordered YAML will be generated instantly.

What is the difference between Deep Recursive and Shallow key sorting?

Deep Recursive sorting traverses through every nested dictionary, object, and mapping at all hierarchy levels. Shallow sorting orders only the top-level root keys while leaving nested mappings untouched.

Are YAML arrays and lists altered during sorting?

By default, sequence order and arrays of objects are preserved exactly as defined. If you enable Sort primitive array elements, scalar arrays of strings or numbers will also be sorted alphabetically.

Why should I sort YAML keys before committing to Git?

Alphabetical key sorting normalizes configuration files, eliminating arbitrary diff noise and preventing merge conflicts when multiple developers or automated CI tools update shared YAML manifests.

Is my YAML data secure when sorting online?

Yes. All parsing and alphabetical sorting logic execute 100% client-side in your browser. Your configuration files, Kubernetes manifests, and secrets never leave your device.

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.