What is sort-json?
The sort-json npm package is a utility for sorting the keys of a JSON object. It helps in maintaining a consistent order of keys, which can be useful for readability, comparison, and version control.
What are sort-json's main functionalities?
Sort JSON keys alphabetically
This feature sorts the keys of a JSON object in alphabetical order. The code sample demonstrates how to use the sort-json package to sort an unsorted JSON object.
const sortJson = require('sort-json');
const unsortedJson = { "b": 2, "a": 1, "c": 3 };
const sortedJson = sortJson(unsortedJson);
console.log(sortedJson); // { "a": 1, "b": 2, "c": 3 }
Sort JSON keys with custom comparator
This feature allows sorting the keys of a JSON object using a custom comparator function. The code sample shows how to sort the keys in reverse alphabetical order.
const sortJson = require('sort-json');
const unsortedJson = { "b": 2, "a": 1, "c": 3 };
const sortedJson = sortJson(unsortedJson, { comparator: (a, b) => b.localeCompare(a) });
console.log(sortedJson); // { "c": 3, "b": 2, "a": 1 }
Sort nested JSON objects
This feature sorts the keys of nested JSON objects. The code sample demonstrates how to sort a JSON object with nested objects.
const sortJson = require('sort-json');
const unsortedJson = { "b": { "d": 4, "c": 3 }, "a": 1 };
const sortedJson = sortJson(unsortedJson, { depth: null });
console.log(sortedJson); // { "a": 1, "b": { "c": 3, "d": 4 } }
Other packages similar to sort-json
sort-keys
The sort-keys package sorts the keys of an object in a similar way to sort-json. It offers options for deep sorting and custom comparators. However, sort-keys is more focused on general object key sorting rather than JSON-specific use cases.
json-stable-stringify
The json-stable-stringify package provides a way to stringify JSON objects with stable key ordering. It ensures that the keys are sorted consistently, which is useful for comparing JSON objects. Unlike sort-json, it focuses on producing a stable string representation rather than directly manipulating JSON objects.
deep-sort-object
The deep-sort-object package sorts the keys of an object deeply, similar to sort-json. It is useful for ensuring consistent key order in deeply nested objects. However, it does not offer as many customization options as sort-json.
sort-json
It takes a JSON file and returns a copy of the same file, but with the sorted keys.
installation
[sudo] npm -g install sort-json
usage
const sortJson = require('sort-json');
const options1 = { ignoreCase: true, reverse: true };
const copy = sortJson({ AA: 123, a: 1, b: 21 }, options1);
sortJson.overwrite('some/absolute/path.json');
sortJson.overwrite(['some/absolute/path1.json', 'some/absolute/path2.json']);
CLI usage
sort-json file.json
=> sorts and overwrites file.json
-i
or --ignore-case
to ignore case when sorting.
-r
or --reverse
to reverse order z -> a
tests
npm test