Reputation: 31
Is there build-in method which can stringify a complex JSON object ?
Every time i use JSON.stringfy I get this error: Converting circular structure to JSON , and also I need its parser
this an image of my object https://i.sstatic.net/eRqKh.jpg
Upvotes: 2
Views: 6218
Reputation: 1333
The standard and best solution is json-stringify-safe module.
Here is the usage (described in module):
var stringify = require('json-stringify-safe');
var circularObj = {};
circularObj.circularRef = circularObj;
circularObj.list = [ circularObj, circularObj ];
console.log(stringify(circularObj, null, 2));
// Output:
{
"circularRef": "[Circular]",
"list": [
"[Circular]",
"[Circular]"
]
}
Upvotes: 0
Reputation: 5480
I recommend Flatted. It's tiny and it works very well. The minified version of it weighs 1KB.
Here's an example from their docs.
var a = [{one: 1}, {two: '2'}];
a[0].a = a;
// a is the main object, will be at index '0'
// {one: 1} is the second object, index '1'
// {two: '2'} the third, in '2', and it has a string
// which will be found at index '3'
Flatted.stringify(a);
// [["1","2"],{"one":1,"a":"0"},{"two":"3"},"2"]
It can then parse the stringified result back if necessary and rebuild the circular references.
var a = [{one: 1}, {two: '2'}]
a[0].a = a
Flatted.stringify(a)
var a1 = Flatted.stringify(a)
var a2 = Flatted.parse(a1)
Upvotes: 1
Reputation: 1332
Take a look at this little library:
https://github.com/WebReflection/circular-json
It serializes and deserializes otherwise valid JSON objects containing circular references into and from a specialized JSON format.
Upvotes: 1
Reputation: 382194
You can't exactly convert a circular structure to JSON : there's nothing to describe those relations that can't just be dumped in a finite time.
Alternatives :
Upvotes: 4