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": "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:

OptionDefaultWhat it does
caseSensitivetrueCapital letters sort before lowercase letters. With false, case is ignored.
naturalfalseCompare numbers in keys by value, so item2 comes before item10.
minKeys2Only check objects with at least this many members.
allowLineSeparatedGroupsfalseA 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": 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"
}