"Too much recursion" error when calling JSON.stringify on a large object with circular dependencies

I have an object that contains circular references, and I would like to look at its JSON representation. For example, if I create this object:

var myObject = {member:{}}; myObject.member.child = {}; myObject.member.child.parent = myObject.member; 

and try to call

 JSON.stringify(myObject); 

I get a "too much recursion" error, which is not surprising. The "child" object has a link to its "parent", and the parent has a link to its child. The JSON representation does not have to be absolutely accurate, since I use it only for debugging, and not for sending data to the server or serializing the object to a file or something like that. Is there a way to tell JSON.stringify to simply ignore certain properties (in this case, the parent property of the child) so that I get:

 { "member" : { "child" : {} } } 

The closest I can think of is to use the getChild() and getParent() methods instead of simple members, because JSON.stringify ignores any properties that are functions, but I would prefer not to do this if I don't have k.

+4
source share
2 answers

You can pass the function as the second argument to stringify. This function receives as arguments the key and value of the element for string encoding. If this function returns undefined, the element will be ignored.

 alert(JSON.stringify(myObject, function(k, v) { return (k === 'member') ? undefined : v; })); 

... or use, for example. firebug or use the toSource () method if you want to see just inside the object.

 alert(myObject.toSource()); 
+8
source

From the crockford implementation (which follows the ECMA specification ):

If the stringify method sees an object that contains the toJSON method, it calls this method and builds the return value. This allows the object to define its own JSON representation.

Then something like this should work fine:

 var myObject = { member: { child: {} } } myObject.member.child.parent = myObject.member; myObject.member.child.toJSON = function () { return 'no more recursion for you.'; }; console.log(JSON.stringify(myObject));​ 

http://jsfiddle.net/feUtk/

+6
source

All Articles