Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

prettier-plugin-sort-json

Gudahtt690.1kMIT4.1.1TypeScript support: included

Prettier plugin to sort JSON files alphanumerically by key

readme

prettier-plugin-sort-json

A plugin for Prettier that sorts JSON files by property name.

Description

This plugin adds a JSON preprocessor that will sort JSON files alphanumerically by key.

By default, top-level object entries are sorted by key lexically using Array.sort, according to each character's Unicode code point value. It can be configured to sort recursively, and with a custom sort order.

Example

Before:

{
  "z": null,
  "a": null,
  "0": null,
  "exampleNestedObject": {
    "z": null,
    "a": null
  }
}

After:

{
  "0": null,
  "a": null,
  "exampleNestedObject": {
    "z": null,
    "a": null
  },
  "z": null
}

Exceptions

  • Non-objects

    This is meant to sort objects. JSON files with a top-level value that is not an object are skipped.

  • JSON files with dedicated Prettier parsers

    This will not sort package.json, package-lock.json, or composer.json. This plugin only affects the json parser used by Prettier. Prettier uses an alternate parser (json-stringify) for those three specific files (See here for details).

  • JSON embedded in other files

    This will not sort JSON objects within other types of files, such as JavaScript or TypeScript files. This is just for sorting JSON files.

Requirements

This module requires an LTS Node version (v16.0.0+), and prettier v3+.

We are maintaining support for Prettier v2 on version 2 of this plugin. See the main-v2 branch for instructions on using v2 of this plugin.

Install

Using npm:

npm install --save-dev prettier-plugin-sort-json

Using yarn:

yarn add --dev prettier-plugin-sort-json

Then follow these instructions to load the plugin.

There are some additional configuration options available (described below), but they are all optional.

Example Prettier configuration

{
  "plugins": ["prettier-plugin-sort-json"]
}

Configuration

These configuration options are all optional. Each option can be set as a CLI flag, or as an entry in your Prettier configuraton (e.g. in your .prettierrc file).

Here is an example .prettierrc file with all default options set:

{
  "plugins": ["prettier-plugin-sort-json"],
  "jsonRecursiveSort": false,
  "jsonSortOrder": "{\"*\": \"lexical\"}"
}

JSON Recursive Sort

Sort JSON objects recursively, including all nested objects. This also sorts objects within JSON arrays.

Default CLI Configuration
false --json-recursive-sort jsonRecursiveSort: <bool>

JSON Sort Order

Use a custom sort order. This is specified as a JSON string that maps exact strings or regular expressions to sorting algorithms.

Default CLI Configuration
"" --json-sort-order '<string>' jsonSortOrder: <string>

Here is an example JSON sort order string:

'{ "placeThisFirst": null, "/^[^\\d+]/": "lexical", "/^\\d+/": "numeric" }'

This sorts the key "placeThisFirst" ahead of all others. After that, the set of all keys that don't start with a number are sorted lexically. Lastly, the set of keys that start with a number are sorted numerically.

Each jsonSortOrder key represents a literal key value or a category of keys, represented by a regular expression. Regular expressions are identified by leading and trailing forward slashes, along with some number of paths optionally following the trailing slash (supported flags are i, m, s, and u).

Each jsonSortOrder value represents the sorting algorithm to use within that category. If the value is null, the default sorting algorithm lexical is used. Here are the supported sorting algorithms:

Sorting Algorithm Description
lexical Sort lexically (i.e. lexicographically). This is the default.
numeric For keys that are prefixed with a number, sort by that number in ascending order. Otherwise sort lexically.
reverseLexical Reverse-order lexical sort.
reverseNumeric Reverse-order numeric sort.
caseInsensitiveLexical Case-insensitive lexical sort.
caseInsensitiveNumeric Case-insensitive numeric sort.
caseInsensitiveReverseLexical Case-insensitive reverse-order lexical sort.
caseInsensitiveReverseNumeric Case-insensitive reverse-order numeric sort.
none Do not sort.

The order of the jsonSortOrder configuration determines how the keys in each category are sorted in relation to each other. Keys that do not match any defined category are treated as being in an implied last category, with lexical sorting.

Note: Escaping can be tricky, especially if you are using regular expression sort keys. These regular expressions are configured as strings, so any backslashes require an additional escape (e.g. notice the double-backslash here: "/^\\d+/").

If this key is configured as part of a JSON Prettier configuration file (prettierrc.json), all double-quotes and backslashes need to be escaped again. For example, the example JSON sort order string would would be "{ \"placeThisFirst\": null, \"/^[^\\\\d+]/\": \"lexical\", \"/^\\\\d+/\": \"numeric\" }.

Ignoring files

This plugin can be used on specific files using Prettier configuration overrides. By configuring this plugin in an override, you can control which files it is applied to. Overrides can also allow using different configuration for different files (e.g. different sort order)

For example, lets say you had the following requirements:

  • No sorting of JSON by default
  • Shallow (non-recursive) sort JSON in the json/ directory
  • Do not sort the file json/unsorted.json
  • Recursively sort recursively-sorted.json

You could do that with this .prettierrc.json file:

{
  "overrides": [
    {
      "excludedFiles": ["./json/unsorted.json"],
      "files": ["./json/**"],
      "options": {
        "plugins": ["prettier-plugin-sort-json"]
      }
    },
    {
      "files": ["./json/recursive-sorted.json"],
      "options": {
        "jsonRecursiveSort": true
      }
    }
  ]
}

Contributing

See CONTRIBUTING.md

changelog

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

Unreleased

4.1.1

Fixed

  • Fix jsonSortOrder validation (#263)
    • The plugin was throwing an error when jsonSortOrder was not set.

4.1.0

Added

  • Export SortJsonOptions and CategorySort types (#256)

Changed

  • Update TypeScript from ~5.1.0 to ~5.5.0 (#238)

4.0.0

Changed

  • BREAKING: Drop support for Node.js v16 (#203)
  • BREAKING: Update case insensitive sort to use deterministic key order (#189)
    • Previously the "case insensitive" sorting options would leave keys in their original order when they differed only in case. They have been updated to sort identical keys in case order instead, making these sort options deterministic.
    • This change has been made because deterministic sort orders tend to be easier to work with, are more aligned with how Prettier works, and typically lead to less churn. However, if your project needs to preserve original key order, you can emulate the old behavior by defining a custom sort order that has a category for each case-insensitive character. For example, you could set this as your prettierrc.js file: `JavaScript prettierrc.js {
      jsonSortOrder: JSON.stringify({
          '/^[Aa]/': 'none',
          '/^[Bb]/': 'none',
          '/^[Cc]/': 'none',
          ...
          '/^[Zz]/': 'none',
      })
      } ` This should work for small character sets. If you require case-insensitive sorting with a larger character set, please submit a feature request. We can bring back the old sorting order as an option if there is demand for it.

3.1.0

Added

  • Add none sorting algorithm (#177)
    • This lets you leave certain properties usorted when defining a custom sort order
    • Contributed by @hyperupcall

3.0.1

Fixed

  • Fix accidental removal of trailing newline (#170)

3.0.0

Changed

  • BREAKING: Migrate to Prettier v3 (#156)
    • This plugin no longer works with Prettier v2. Prettier v2 support will be maintained on v2 of this plugin however.
    • Prettier v3 will no longer automatically load plugins. Follow these instructions to load this plugin after updating.

2.0.0

Changed

1.0.0

Changed

  • BREAKING: Change jsonSortOrder option to a JSON string (#118)
    • This configuration option used to accept a file path. Now it accepts a JSON string instead. See the README for more details.

0.0.3

Added

  • Add jsonSortOrder option (#92)
    • This also supports case-insensitive sorting (#104)

Changed

  • BREAKING: Rewrite plugin to sort AST (#100)
    • This ensures that symbols are sorted before numbers, as in a normal lexical sort. This is the breaking change, because the sort order may have changed in some edge cases.
    • This ensures that JSON files with mistakes like trailing commas are still sorted properly the first time.
  • BREAKING: Update minimum Node.js version to v14 (#40, #61)
  • BREAKING: Update minimum Prettier version to v2.3.2 (#47)

0.0.2 - 2021-02-13

Added

  • JSON Recursive Sort option (#23)

Changed

  • [BREAKING] Update minimum prettier version to v2.1.0 (#21, #24)
  • [BREAKING] Move prettier from dependencies to peerDependencies (#22)
  • Fix manifest repository property (#17)

Removed

  • Remove unused @babel/types dependency (#20)

0.0.1 - 2020-09-22

Added

  • Initial release