Stringify (convert to JSON) a JavaScript object with circular reference Stringify (convert to JSON) a JavaScript object with circular reference json json

Stringify (convert to JSON) a JavaScript object with circular reference


Circular structure error occurs when you have a property of the object which is the object itself directly (a -> a) or indirectly (a -> b -> a).

To avoid the error message, tell JSON.stringify what to do when it encounters a circular reference.For example, if you have a person pointing to another person ("parent"), which may (or may not) point to the original person, do the following:

JSON.stringify( that.person, function( key, value) {  if( key == 'parent') { return value.id;}  else {return value;}})

The second parameter to stringify is a filter function. Here it simply converts the referred object to its ID, but you are free to do whatever you like to break the circular reference.

You can test the above code with the following:

function Person( params) {  this.id = params['id'];  this.name = params['name'];   this.father = null;  this.fingers = [];  // etc.}var me = new Person({ id: 1, name: 'Luke'});var him = new Person( { id:2, name: 'Darth Vader'});me.father = him; JSON.stringify(me); // so far so goodhim.father = me; // time travel assumed :-)JSON.stringify(me); // "TypeError: Converting circular structure to JSON"// But this should do the job:JSON.stringify(me, function( key, value) {  if(key == 'father') {     return value.id;  } else {    return value;  };});

BTW, I'd choose a different attribute name to "parent" since it is a reserved word in many languages (and in DOM). This tends to cause confusion down the road...


It appears that dojo can represent circular references in JSON in the form : {"id":"1","me":{"$ref":"1"}}

Here is an example:

http://jsfiddle.net/dumeG/

require(["dojox/json/ref"], function(){    var me = {        name:"Kris",        father:{name:"Bill"},        mother:{name:"Karen"}    };    me.father.wife = me.mother;    var jsonMe = dojox.json.ref.toJson(me); // serialize me    alert(jsonMe);});​

Produces:

{   "name":"Kris",   "father":{     "name":"Bill",     "wife":{          "name":"Karen"      }   },   "mother":{     "$ref":"#father.wife"   }}

Note: You can also de-serialize these circular referenced objects using the dojox.json.ref.fromJson method.

Other Resources:

How to serialize DOM node to JSON even if there are circular references?

JSON.stringify can't represent circular references


No-lib

Use below replacer to generate json with string references (similar json-path) to duplicate/circular referenced objects

let s = JSON.stringify(obj, refReplacer());