W3cubDocs

/JavaScript

Errors: Cyclic object value

Message

TypeError: cyclic object value (Firefox)
TypeError: Converting circular structure to JSON (Chrome)

Error type

TypeError

What went wrong?

When calling JSON.stringify() cyclic object reference structures can't be converted to a string.

Examples

In a circular structure like the following

var a = {};
var b = {}; 
a.child = b;
b.child = a;

JSON.stringify() will fail

JSON.stringify(a);
// TypeError: cyclic object value

You will need to check for cyclic object references before stringifying. For example by specifying a replacer function as the second argument of JSON.stringify().

seen = []; 

var replacer = function(key, value) {
  if (value != null && typeof value == "object") {
    if (seen.indexOf(value) >= 0) {
      return;
    }
    seen.push(value);
  }
  return value;
};

JSON.stringify(a, replacer); 
// "{"child":{}}"

Or, you can use a library or utility functions that have already been written for this scenario. For example, there is cycle.js by Douglas Crockford.

See also

  • JSON.stringify
  • cycle.js – Introduces two functions, JSON.decycle and JSON.retrocycle, which make it possible to encode cyclical structures and dags in JSON, and to then recover them.

© 2005–2017 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value