json-stable-stringify
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|---|---|---|---|---|
jsonify | 0.0.1 | 7.27 kB | Public Domain | prod | 1 1 |
The npm package json-stable-stringify is designed to offer a deterministic version of JSON.stringify(). It allows users to get consistent hashes from stringified results. This tool is ideal for times you need predictability in your JSON strings, ensuring that they are consistently structured and will always produce the same output when given the same input.
Using json-stable-stringify is straightforward. You first need to install it via npm with the command npm install json-stable-stringify
. Once installed, you can require it in your JavaScript code as follows:
var stringify = require('json-stable-stringify');
var obj = { c: 8, b: [{ z: 6, y: 5, x: 4 }, 7], a: 3 };
console.log(stringify(obj));
// Outputs: {"a":3,"b":[{"x":4,"y":5,"z":6},7],"c":8}
You can pass in custom comparison functions to sort the keys according to your need:
var s = stringify(obj, function (a, b) {
return b.key.localeCompare(a.key);
});
console.log(s);
// Outputs: {"c":8,"b":[{"z":6,"y":5,"x":4},7],"a":3}
In addition, prettifying your stringified output is also feasible by specifying the space in the options:
var s = stringify(obj, { space: ' ' });
console.log(s);
// Outputs:
// {
// "a": {
// "and": [
// 1,
// 2,
// 3
// ],
// "foo": "bar"
// },
// "b": 1
// }
The detailed documentation and instructions for json-stable-stringify can be found on its GitHub page: https://github.com/ljharb/json-stable-stringify. This README.md file includes all the necessary guidelines, from installation to options and methods you can employ to customize the function’s behavior, such as the comparison function, replacer, and space.