How to Sort JSON Keys in Java, C#, Go, Ruby, PHP, Rust — Code Patterns and the Browser Shortcut
- Every major language has a pattern for sorting JSON keys — Java uses TreeMap, C# uses JObject.Properties.OrderBy, Go sorts map keys manually.
- For production code, pick the idiomatic library pattern and stick with it.
- For one-off work, the browser tool bypasses all of them.
Table of Contents
Every language handles JSON differently, and every language's "sort the keys" recipe is slightly different. This post is the consolidated reference: how to alphabetize JSON keys in Java, C#, Go, Ruby, PHP, and Rust — and when to skip all of them and use our browser-based JSON Sorter instead.
The browser tool is faster for one-time sorting. The language-specific patterns are right when you need sort as part of a service, CLI, or build step.
Java — Jackson and TreeMap
Jackson, the most widely used Java JSON library, supports key sorting out of the box:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
String sortedJson = mapper.writeValueAsString(yourObject);
This sorts Map keys alphabetically when serializing. Recursive — nested maps also get sorted.
For Gson users:
// Gson does not sort natively. Convert to a TreeMap first:
TreeMap<String, Object> sorted = new TreeMap<>(yourMap);
String json = new Gson().toJson(sorted);
For deeply nested JSON, you need a recursive TreeMap helper. Most teams use Jackson precisely to avoid writing it.
C# — Newtonsoft.Json and System.Text.Json
Newtonsoft.Json (still the most common choice for legacy .NET):
var jObject = JObject.Parse(jsonString);
var sorted = new JObject(jObject.Properties().OrderBy(p => p.Name));
string output = sorted.ToString();
For recursion across nested objects, walk the tree:
JToken SortToken(JToken token) {
if (token is JObject obj) {
return new JObject(obj.Properties().OrderBy(p => p.Name)
.Select(p => new JProperty(p.Name, SortToken(p.Value))));
}
if (token is JArray arr) return new JArray(arr.Select(SortToken));
return token;
}
For System.Text.Json (modern .NET), there is no built-in sort option. You have to round-trip through a sorted dictionary or use a custom JsonConverter. Most developers use Newtonsoft for this reason alone.
Go — Sort Map Keys Manually
Go's encoding/json package sorts map keys alphabetically by default when marshaling:
data := map[string]interface{}{"zebra": 1, "alpha": 2}
jsonBytes, _ := json.Marshal(data)
// Output: {"alpha":2,"zebra":1}
This is recursive. Nested maps are also sorted.
The gotcha: Go structs marshal in field declaration order, not alphabetical. If you have a struct with fields declared as Zebra, Alpha, the output is {"Zebra":...,"Alpha":...}. To sort struct output, convert to map[string]interface{} first or reorder the struct field declarations.
For mixed struct + map output, the idiomatic pattern is to build a map[string]interface{} from the struct, then marshal that.
Ruby and PHP
Ruby: The json library does not have a sort option, but you can sort a hash first:
require 'json'
sorted = hash.sort.to_h # top-level only
def deep_sort(obj)
case obj
when Hash then obj.sort.to_h.transform_values { |v| deep_sort(v) }
when Array then obj.map { |i| deep_sort(i) }
else obj
end
end
puts JSON.pretty_generate(deep_sort(data))
PHP: Use ksort + recursion:
function sortRecursive(&$arr) {
if (is_array($arr)) {
ksort($arr);
foreach ($arr as &$val) sortRecursive($val);
}
}
$data = json_decode($jsonString, true);
sortRecursive($data);
echo json_encode($data, JSON_PRETTY_PRINT);
Both languages lack a built-in "sort on encode" flag, which is why these helpers are common.
Rust — serde_json
Rust's serde_json uses Map (IndexMap preserving insertion order) for JSON objects. To sort keys:
use serde_json::{Value, Map};
fn sort_value(v: Value) -> Value {
match v {
Value::Object(m) => {
let mut sorted: Map<String, Value> = Map::new();
let mut keys: Vec<_> = m.keys().cloned().collect();
keys.sort();
for k in keys {
let val = m[&k].clone();
sorted.insert(k, sort_value(val));
}
Value::Object(sorted)
}
Value::Array(arr) => Value::Array(arr.into_iter().map(sort_value).collect()),
other => other,
}
}
For quick output, serde_json has a to_string_pretty() function that works with any sorted Value.
When the Browser Tool Beats All of These
Every language-specific code block above is 5-20 lines plus the overhead of running the code. For a one-off sort, all of that is more work than needed.
Scenarios where the browser wins:
1. Debugging a payload — you received JSON, want to alphabetize it to find a field.
2. Code review — a colleague sent you a config to check; sort it, scan it, comment on it.
3. Prototyping — before you write the full language-specific sort in your app, verify the shape in the browser.
4. Polyglot environments — different services use different languages; sort the canonical JSON once in the browser, share it.
5. Quick sanity checks — is my config well-formed after sorting? Paste, sort, validate visually.
The language patterns above are the right answer when sorting is part of your app. The browser is the right answer when it's something you do manually.
Sort JSON Across Any Language
Skip the language-specific code for one-off sorting. Paste and click.
Open Free JSON Key SorterFrequently Asked Questions
Does Go encoding/json sort keys by default?
Yes, for map[string]interface{} types — Go marshals map keys in alphabetical order automatically. For structs, fields are marshaled in declaration order, which may not match alphabetical. Convert structs to maps first if you need guaranteed alphabetical output.
How do I sort JSON keys with Newtonsoft.Json recursively?
Use the recursive JToken sort helper shown above — Parse to JObject, walk with a recursive function that rebuilds objects with OrderBy on property names. For deeply nested JSON, this is the idiomatic pattern.
Is there a one-liner for sorting JSON in PHP?
Not exactly one line, but close: json_encode(ksort_recursive(json_decode($jsonString, true))). You still need the recursive ksort helper since PHP ksort only sorts one level.
Does Jackson sort keys of all JSON or only Maps?
With ORDER_MAP_ENTRIES_BY_KEYS, Jackson sorts Map keys. For JavaBean fields (POJOs), declaration order is used. If you need alphabetized JSON output from POJOs, either annotate field order, or serialize to a Map first.

