json/sort-keys
Require JSON object keys to be sorted
fixable
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:
eslint.config.js
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#
example.json1 problem
{
"name": "app",
"license"Expected object keys to be in alphanumeric case-sensitive ascending order. license should be before name.: "MIT"
}example.jsonNo problems
{
"license": "MIT",
"name": "app",
"scripts": { "build": "bun build", "test": "bun test" }
}Options#
eslint.config.js
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:
example.json1 problem
{ "item2": 5, "item10"Expected object keys to be in alphanumeric case-sensitive ascending order. item10 should be before item2.: 9 }With natural it isn't:
example.jsonwith
"asc", { "natural": true }No problems{ "item2": 5, "item10": 9 }Not reported with allowLineSeparatedGroups:
example.jsonwith
"asc", { "allowLineSeparatedGroups": true }No problems{
"id": 1,
"name": "Ada",
"city": "London",
"country": "UK"
}