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?
- Paste or Upload YAML Payload: Paste your YAML configuration into the left Raw YAML Input editor, click Upload, or click Sample.
- 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.
- 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.yamlfile.
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.yamlPython
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.");
}
}