]> git.r.bdr.sh - rbdr/dotfiles/blame - atom/packages/pretty-json/node_modules/json-stable-stringify/readme.markdown
Remove mc config
[rbdr/dotfiles] / atom / packages / pretty-json / node_modules / json-stable-stringify / readme.markdown
CommitLineData
06a3d686
BB
1# json-stable-stringify
2
3deterministic version of `JSON.stringify()` so you can get a consistent hash
4from stringified results
5
6You can also pass in a custom comparison function.
7
8[![browser support](https://ci.testling.com/substack/json-stable-stringify.png)](https://ci.testling.com/substack/json-stable-stringify)
9
10[![build status](https://secure.travis-ci.org/substack/json-stable-stringify.png)](http://travis-ci.org/substack/json-stable-stringify)
11
12# example
13
14``` js
15var stringify = require('json-stable-stringify');
16var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 };
17console.log(stringify(obj));
18```
19
20output:
21
22```
23{"a":3,"b":[{"x":4,"y":5,"z":6},7],"c":8}
24```
25
26# methods
27
28``` js
29var stringify = require('json-stable-stringify')
30```
31
32## var str = stringify(obj, opts)
33
34Return a deterministic stringified string `str` from the object `obj`.
35
36## options
37
38### cmp
39
40If `opts` is given, you can supply an `opts.cmp` to have a custom comparison
41function for object keys. Your function `opts.cmp` is called with these
42parameters:
43
44``` js
45opts.cmp({ key: akey, value: avalue }, { key: bkey, value: bvalue })
46```
47
48For example, to sort on the object key names in reverse order you could write:
49
50``` js
51var stringify = require('json-stable-stringify');
52
53var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 };
54var s = stringify(obj, function (a, b) {
55 return a.key < b.key ? 1 : -1;
56});
57console.log(s);
58```
59
60which results in the output string:
61
62```
63{"c":8,"b":[{"z":6,"y":5,"x":4},7],"a":3}
64```
65
66Or if you wanted to sort on the object values in reverse order, you could write:
67
68```
69var stringify = require('json-stable-stringify');
70
71var obj = { d: 6, c: 5, b: [{z:3,y:2,x:1},9], a: 10 };
72var s = stringify(obj, function (a, b) {
73 return a.value < b.value ? 1 : -1;
74});
75console.log(s);
76```
77
78which outputs:
79
80```
81{"d":6,"c":5,"b":[{"z":3,"y":2,"x":1},9],"a":10}
82```
83
84### space
85
86If you specify `opts.space`, it will indent the output for pretty-printing.
87Valid values are strings (e.g. `{space: \t}`) or a number of spaces
88(`{space: 3}`).
89
90For example:
91
92```js
93var obj = { b: 1, a: { foo: 'bar', and: [1, 2, 3] } };
94var s = stringify(obj, { space: ' ' });
95console.log(s);
96```
97
98which outputs:
99
100```
101{
102 "a": {
103 "and": [
104 1,
105 2,
106 3
107 ],
108 "foo": "bar"
109 },
110 "b": 1
111}
112```
113
114# install
115
116With [npm](https://npmjs.org) do:
117
118```
119npm install json-stable-stringify
120```
121
122# license
123
124MIT