PDA

View Full Version : JSON encode objects with circular references



krause
23 Sep 2010, 1:25 PM
I found this (http://www.sencha.com/forum/showthread.php?1279-YAHOO.ext.util.JSON.encode()-infinite-loop-on-CustomEvents&highlight=json+encode+circular) antique thread and this (http://www.sencha.com/forum/showthread.php?58378-Solved-Problem-With-Ext.util.JSON.encode&highlight=json+encode+circular) other regarding this issues but in the first case Jack says "there's no easy way to detect" a circular reference while the other thread deals more with the fact that someone was trying to encode an object that shouldn't.
In my case the objects I'm trying to serialize are pure data objects (i.e. not Ext components or Records or stuff with behaviour), but they do have circular references.

Example:


var a = {name : 'a'};
var b = {name : 'b', a : a};
a.b = b;

In this case, when I call
Ext.util.JSON.encode(a); I get an "InternalError: too much recursion".

I patched the encode function to keep track of the objects that have already bee encoded so that if I detect the same object again (using === ) I just skip it (setting the property value to null).

It seems to work fine, at least for simple cases, but given the very few post regarding this issue I was wondering if there is something fundamentally flawed in having circular references in the first place.

Regards