I have an object (parse tree) that contains child nodes which are references to other nodes.
I'd like to serialize this object, using JSON.stringify()
, but I get : TypeError: cyclic object value
because of the constructs I mentioned.
How could I work around this? It does not matter to me whether these references to other nodes are represented or not in the serialized object.
On the other hand, removing these properties from the object when they are being created seems tedious and I wouldn't want to make changes to the parser (narcissus).
I've created an GitHub Gist which is able to detect cyclic structures and also de- and encodes them: https://gist.github.com/Hoff97/9842228
To transform just use JSONE.stringify/JSONE.parse. It also de- and encodes functions. If you want to disable this just remove lines 32-48 and 61-85.
You can find an example fiddle here:
http://jsfiddle.net/hoff97/7UYd4/
A precondition was missing, otherwise the integer values in array objects are truncated, i.e. [[ 08.11.2014 12:30:13, 1095 ]] 1095 gets reduced to 095.
much saver and it shows where an cycle object was.
produces
I create too a github project that can serialize cyclic object and restore the class if you save it in the serializename attribute like a String
https://github.com/bormat/serializeStringifyParseCyclicObject
Edit: I have transform my script for NPM https://github.com/bormat/borto_circular_serialize and I have change function names from french to english.
Use the second parameter of
stringify
, the replacer function, to exclude already serialized objects:http://jsfiddle.net/mH6cJ/38/
As correctly pointed out in other comments, this code removes every "seen" object, not only "recursive" ones.
For example, for:
the result will be incorrect. If your structure is like this, Crockford's decycle is a better option.