Sort JSON keys alphabetically at all levels (for example for sorting package-lock.json
).
Requires node@14
or higher:
npm install sort-json-keys --save-dev
Sort all keys in the foo.json
file in alphabetical order, indented by two spaces (default indentation):
npx sort-json-keys foo.json
Sorting the keys does not change the JS value of the JSON. In particular, array elements are not sorted.
For example this converts a JSON-file
{ "b": 1, "a": { "y": 2, "x": 3 }, "c": ["b", "a"] }
to a file
{
"a": {
"x": 3,
"y": 2
},
"b": 1,
"c": [
"b",
"a"
]
}
Sort all keys in foo.json
and baz/bar.json
files in alphabetical order, indented by two spaces:
npx sort-json-keys foo.json baz/bar.json
Sort all keys in foo.json
and bar.json
files, indented by four spaces:
npx sort-json-keys foo.json bar.json --indent 4
Sort all keys in foo.json
files without indentation (as a one-line file):
npx sort-json-keys foo.json --indent 0
import sortJsonKeys from "sort-json-keys";
// or
import { sortJsonKeys } from "sort-json-keys";
const json = { b: 1, a: 2 };
const sortedJson = sortJsonKeys(json); // { a: 2, b: 1 }