Muhammed Abd El-Wadod
Muhammed Abd El-Wadod

Reputation: 31

how to stringify circular JSON object?

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

Answers (4)

Gagan
Gagan

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

Mig82
Mig82

Reputation: 5480

I recommend Flatted. It's tiny and it works very well. The minified version of it weighs 1KB.

enter image description here

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)

enter image description here

Upvotes: 1

zenw0lf
zenw0lf

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

Denys Séguret
Denys Séguret

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 :

  • use another format than JSON (for example YAML as suggested by Armadan)
  • extend JSON with an additional JSON compatible syntax to describe references
  • use a library removing the circular references (producing some JSON but without what can't be stringified). I made such a library : https://github.com/Canop/JSON.prune

Upvotes: 4

Related Questions