Message
TypeError: cyclic object value (Firefox) TypeError: Converting circular structure to JSON (Chrome)
Error type
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
andJSON.retrocycle
, which make it possible to encode cyclical structures and dags in JSON, and to then recover them.