Linter · Rules
json/sort-keys
Require JSON object keys to be sorted
In a long object, sorted keys are quick to find, and two people who add a key put it in the same place.
Each key is compared with the one before it. --fix swaps the two members, and runs again until the object is sorted. It skips a member that has a comment next to it, because it can't tell which member the comment belongs to.
Configure
Off by default. It needs an ESLint config that says which files are in the language:
import json from "@eslint/json";
export default [
{
files: ["**/*.json"],
plugins: { json },
language: "json/json",
rules: { "json/sort-keys": "error" },
},
];
It also works with json/jsonc and json/json5.
Examples
Reported:
{
"name": "app",
"license": "MIT"
}
Not reported:
{
"license": "MIT",
"name": "app",
"scripts": { "build": "bun build", "test": "bun test" }
}
Options
export default [
{
rules: { "json/sort-keys": ["error", "asc", { natural: true, minKeys: 5 }] },
},
];
The first option is the direction: "asc" (default) or "desc". The second is an object:
| Option | Default | What it does |
|---|---|---|
caseSensitive | true | Capital letters sort before lowercase letters. With false, case is ignored. |
natural | false | Compare numbers in keys by value, so item2 comes before item10. |
minKeys | 2 | Only check objects with at least this many members. |
allowLineSeparatedGroups | false | A blank line between members starts a new group that's sorted separately. |
By default item10 sorts before item2, character by character, so this is reported:
{ "item2": 5, "item10": 9 }
With natural it isn't:
{ "item2": 5, "item10": 9 }
Not reported with allowLineSeparatedGroups:
{
"id": 1,
"name": "Ada",
"city": "London",
"country": "UK"
}