# 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.

{/* Generated by src/codegen/lint-rule-docs.ts. Do not edit this section. */}

## Configure

Off by default. It needs an ESLint config that says which files are in the language:

{/* skip */}

```js 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`.

{/* End of the generated section. */}

## Examples

Reported:

{/* bad */}

```json
{
  "name": "app",
  "license": "MIT"
}
```

Not reported:

{/* good */}

```json
{
  "license": "MIT",
  "name": "app",
  "scripts": { "build": "bun build", "test": "bun test" }
}
```

## Options

{/* skip */}

```js 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:

{/* bad */}

```json
{ "item2": 5, "item10": 9 }
```

With `natural` it isn't:

{/* good {"options": ["asc", {"natural": true}]} */}

```json
{ "item2": 5, "item10": 9 }
```

Not reported with `allowLineSeparatedGroups`:

{/* good {"options": ["asc", {"allowLineSeparatedGroups": true}]} */}

```json
{
  "id": 1,
  "name": "Ada",

  "city": "London",
  "country": "UK"
}
```
