1 # json-stable-stringify
3 deterministic version of `JSON.stringify()` so you can get a consistent hash
4 from stringified results
6 You can also pass in a custom comparison function.
8 [![browser support](https://ci.testling.com/substack/json-stable-stringify.png)](https://ci.testling.com/substack/json-stable-stringify)
10 [![build status](https://secure.travis-ci.org/substack/json-stable-stringify.png)](http://travis-ci.org/substack/json-stable-stringify)
15 var stringify = require('json-stable-stringify');
16 var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 };
17 console.log(stringify(obj));
23 {"a":3,"b":[{"x":4,"y":5,"z":6},7],"c":8}
29 var stringify = require('json-stable-stringify')
32 ## var str = stringify(obj, opts)
34 Return a deterministic stringified string `str` from the object `obj`.
40 If `opts` is given, you can supply an `opts.cmp` to have a custom comparison
41 function for object keys. Your function `opts.cmp` is called with these
45 opts.cmp({ key: akey, value: avalue }, { key: bkey, value: bvalue })
48 For example, to sort on the object key names in reverse order you could write:
51 var stringify = require('json-stable-stringify');
53 var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 };
54 var s = stringify(obj, function (a, b) {
55 return a.key < b.key ? 1 : -1;
60 which results in the output string:
63 {"c":8,"b":[{"z":6,"y":5,"x":4},7],"a":3}
66 Or if you wanted to sort on the object values in reverse order, you could write:
69 var stringify = require('json-stable-stringify');
71 var obj = { d: 6, c: 5, b: [{z:3,y:2,x:1},9], a: 10 };
72 var s = stringify(obj, function (a, b) {
73 return a.value < b.value ? 1 : -1;
81 {"d":6,"c":5,"b":[{"z":3,"y":2,"x":1},9],"a":10}
86 If you specify `opts.space`, it will indent the output for pretty-printing.
87 Valid values are strings (e.g. `{space: \t}`) or a number of spaces
93 var obj = { b: 1, a: { foo: 'bar', and: [1, 2, 3] } };
94 var s = stringify(obj, { space: ' ' });
116 With [npm](https://npmjs.org) do:
119 npm install json-stable-stringify