Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

circumvent ERROR Converting circular structure to JSON when doing JSON.stringify()?

For debugging I want to serialize javascript objects with JSON.stringify(myobject). But this gives:

TypeError: Converting circular structure to JSON

Is there a way to prevent this, by for instance pruning the output tree?

Some more background:

I want to collect some data on different objects and see what is going on, and why a feature works for one situation but not for another. By comparing outputs I hope to be able to find differences which explains why it is not working in "another" situation. I'm using jquery and my debug horse is called chrome. If there are better alternatives for doing this type of debugging activities I'm also very much interested!

Cheers, jeroen.

like image 203
dr jerry Avatar asked Mar 23 '11 18:03

dr jerry


People also ask

How do you prevent converting circular structure to JSON?

The "Converting circular structure to JSON" error occurs when we pass an object that contains circular references to the JSON. stringify() method. To solve the error, make sure to remove any circular references before converting the object to JSON.

How do you convert circular structure to string?

A circular structure is an object that references itself. To be able to stringify such objects, developers can utilize the replacer parameter in the stringify() method, making sure the function that is being passed in, filters out repeated or circular data.

Can JSON Stringify throw an error?

Errors and Edge CasesJSON. stringify() throws an error when it detects a cyclical object. In other words, if an object obj has a property whose value is obj , JSON. stringify() will throw an error.

What is the return type of JSON Stringify?

Return Value: It returns a string for a given value. Example: The below is the example of the JSON stringify() Method.


2 Answers

JSON.stringify(obj) does not support circular referencing such as:

var car = {}
car.myself = car;
JSON.stringify(car);

However dojox.json.ref does support circular referencing, if you wanted to explore another option.

However if your purposes are strictly to debug, I'd suggest using the built in browser debugger such as Chrome's, IE's or Firebug(for firefox).

like image 164
Mike Lewis Avatar answered Oct 11 '22 14:10

Mike Lewis


You can use console.log() and the chrome javascript debug console, which will happily let you inspect your object even if it has cyclic references.

like image 25
Rob Neuhaus Avatar answered Oct 11 '22 14:10

Rob Neuhaus