[6a3a178] | 1 | # json-stringify-safe
|
---|
| 2 |
|
---|
| 3 | Like JSON.stringify, but doesn't throw on circular references.
|
---|
| 4 |
|
---|
| 5 | ## Usage
|
---|
| 6 |
|
---|
| 7 | Takes the same arguments as `JSON.stringify`.
|
---|
| 8 |
|
---|
| 9 | ```javascript
|
---|
| 10 | var stringify = require('json-stringify-safe');
|
---|
| 11 | var circularObj = {};
|
---|
| 12 | circularObj.circularRef = circularObj;
|
---|
| 13 | circularObj.list = [ circularObj, circularObj ];
|
---|
| 14 | console.log(stringify(circularObj, null, 2));
|
---|
| 15 | ```
|
---|
| 16 |
|
---|
| 17 | Output:
|
---|
| 18 |
|
---|
| 19 | ```json
|
---|
| 20 | {
|
---|
| 21 | "circularRef": "[Circular]",
|
---|
| 22 | "list": [
|
---|
| 23 | "[Circular]",
|
---|
| 24 | "[Circular]"
|
---|
| 25 | ]
|
---|
| 26 | }
|
---|
| 27 | ```
|
---|
| 28 |
|
---|
| 29 | ## Details
|
---|
| 30 |
|
---|
| 31 | ```
|
---|
| 32 | stringify(obj, serializer, indent, decycler)
|
---|
| 33 | ```
|
---|
| 34 |
|
---|
| 35 | The first three arguments are the same as to JSON.stringify. The last
|
---|
| 36 | is an argument that's only used when the object has been seen already.
|
---|
| 37 |
|
---|
| 38 | The default `decycler` function returns the string `'[Circular]'`.
|
---|
| 39 | If, for example, you pass in `function(k,v){}` (return nothing) then it
|
---|
| 40 | will prune cycles. If you pass in `function(k,v){ return {foo: 'bar'}}`,
|
---|
| 41 | then cyclical objects will always be represented as `{"foo":"bar"}` in
|
---|
| 42 | the result.
|
---|
| 43 |
|
---|
| 44 | ```
|
---|
| 45 | stringify.getSerialize(serializer, decycler)
|
---|
| 46 | ```
|
---|
| 47 |
|
---|
| 48 | Returns a serializer that can be used elsewhere. This is the actual
|
---|
| 49 | function that's passed to JSON.stringify.
|
---|
| 50 |
|
---|
| 51 | **Note** that the function returned from `getSerialize` is stateful for now, so
|
---|
| 52 | do **not** use it more than once.
|
---|