I have a big object I want to convert to JSON and send. However it has circular structure. I want to toss whatever circular references exist and send whatever can be stringified. How do I do that?
Thanks.
var obj = {
a: "foo",
b: obj
}
I want to stringify obj into:
{"a":"foo"}
I found circular-json library on github and it worked well for my problem.
Some good features I found useful:
just do
then in your js file
You could also do
https://github.com/WebReflection/circular-json
NOTE: I have nothing to do with this package. But I do use it for this.
I know this is an old question, but I'd like to suggest an NPM package I've created called smart-circular, which works differently from the other ways proposed. It's specially useful if you're using big and deep objects.
Some features are:
Replacing circular references or simply repeated structures inside the object by the path leading to its first occurrence (not just the string [circular]);
By looking for circularities in a breadth-first search, the package ensures this path is as small as possible, which is important when dealing with very big and deep objects, where the paths can get annoyingly long and difficult to follow (the custom replacement in JSON.stringify does a DFS);
Allows personalised replacements, handy to simplify or ignore less important parts of the object;
Finally, the paths are written exactly in the way necessary to access the field referenced, which can help you debugging.
I wonder why nobody posted the proper solution from MDN page yet...
Seen values should be stored in a set, not in array (replacer gets called on every element) and there is no need to try
JSON.stringify
each element in the chain leading to a circular reference.Like in the accepted answer, this solution removes all repeating values, not just the circular ones. But at least it does not have exponential complexity.
I really liked Trindaz's solution - more verbose, however it had some bugs. I fixed them for whoever likes it too.
Plus, I added a length limit on my cache objects.
If the object I am printing is really big - I mean infinitely big - I want to limit my algorithm.
evaluates to:
with the function: