sorted-json

Sort keys and array elements in a JSON.

MIT 10 个版本
安装
npm install sorted-json
yarn add sorted-json
pnpm add sorted-json
bun add sorted-json
README

sorted-json-js

Sort keys and array elements in a JSON.

Quick Example 1:

Using .sortify(...) with { sortArray: true } options to sort an object:

var sortedJSON = require('sorted-json');

var obj_1 = {
  numberArray: [3, 1, 2],
  anotherJSON: {
    stringArray: ['cat', 'book', 'apple'],
    numberA: 2,
    numberB: 1
  },
  number1: 2,
  number2: 1
};
console.log(sortedJSON.sortify(obj_1, { sortArray: true }));

Output:

{
  anotherJSON: { numberA: 2, numberB: 1, stringArray: [ 'apple', 'book', 'cat' ] },
  number1: 2,
  number2: 1,
  numberArray: [ 1, 2, 3 ]
}

Quick Example 2:

Using .stringify(...) to get a sorted JSON string:

var obj_2 = {
  numberArray: [3, 1, 2],
  anotherJSON: {
    stringArray: ['cat', 'book', 'apple'],
    numberA: 2,
    numberB: 1
  },
  number1: 2,
  number2: 1
};
console.log(sortedJSON.stringify(obj_2));

Output:

{"anotherJSON":{"numberA":2,"numberB":1,"stringArray":["cat","book","apple"]},"number1":2,"number2":1,"numberArray":[3,1,2]}

API:

.sortify(obj [, options])

Sort an object and return it.

Parameter Type Required Default Description
obj object Yes The object to sort
options object {} Sort options
options.sortBy function undefined Specifies a function that defines the sort order. Same to compareFunction parameter in Array.prototype.sort(compareFunction)
options.sortKey boolean true Sort the keys in obj or not
options.sortArray boolean true Sort the array elements in `obj or not
options.stringify boolean false Output the stringified obj or not (Using JSON.stringify())
options.replacer Parameter for JSON.stringify()
options.space Parameter for JSON.stringify()

.stringify(obj)

Parameter Type Required Default Description
obj object Yes The object to sort

Install:

npm install sorted-json

Test:

npm test

License

MIT

版本列表
0.3.0 2024-12-26
0.2.6 2019-06-18
0.2.5 2019-03-26
0.2.3 2018-09-26
0.2.2 2017-07-06
0.2.1 2017-01-06
0.2.0 2017-01-06
0.1.2 2015-08-28
0.1.1 2015-08-28
0.1.0 2015-08-28