Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting circular structure to JSON -- Any way to find what field it is complaining about?

I'm trying to stringify(...) an object in Chrome, and I keep getting a "Converting circular structure to JSON" message, despite the fact that (as far as I know) no such structure exists.

I've been over the code a dozen times and can't find any circular references whatsoever. Is there any way to get Chrome to tell me what it's bitching about beyond this painfully useless error message?

like image 225
Mike Avatar asked Aug 10 '11 02:08

Mike


People also ask

How do you resolve 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.

What is circular structure in JSON?

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.

Is JSON Stringify safe?

stringify() is fine. Using the output of JSON. stringify() in a JavaScript context will result in the expected behavior.


2 Answers

Pardon me if this is too obvious. At the time of writing, I dont know what you have tried.

insert

console.log(the object);  

replacing 'the object' with the object you are passing to JSON.stringify()

insert this line before the JSON.stringify call

and look in the console log (shift control J) for the object. In the console log the object will be tagged with a ">" symbol which can be clicked to expand to the fields.

It is complaining about an object that has pointers into itself, like this kind of object:

A = []; A[0] = A;  JSON.stringify(A); // circular error 
like image 106
Paul Avatar answered Oct 24 '22 22:10

Paul


You can use dojox.json.ref to find circular references. This code prints json representation of your objectWithCircularReferences:

require(["dojox/json/ref"], function(){     console.log(dojox.json.ref.toJson(objectWithCircularReferences)); }); 

Any occurence of "$ref" substring in its output to console will help you locate circular references. You can alternatively pipe this json output to global variable ZZZ like this if you wish:

require(["dojox/json/ref"], function(){     window.ZZZ = dojox.json.ref.toJson(objectWithCircularReferences); }); 

And of course you need to include dojo library beforehand. In an html file:

<script src="//yandex.st/dojo/1.9.1/dojo/dojo.js"></script> 

In firebug console:

include("//yandex.st/dojo/1.9.1/dojo/dojo.js") 

In Chrome console:

SCRIPT = document.createElement('script'); SCRIPT.src = '//yandex.st/dojo/1.9.1/dojo/dojo.js'; document.body.appendChild(SCRIPT); 
like image 40
user2683246 Avatar answered Oct 24 '22 22:10

user2683246