TypeError: cyclic object value (Firefox) TypeError: Converting circular structure to JSON (Chrome and Opera) TypeError: Circular reference in value argument not supported (Edge)
什么问题?
该 JSON 格式本身不支持对象引用(虽然存在IETF草案),因此JSON.stringify()不会尝试解决这些问题,并相应地失败。
// Demo: Circular referencevar o = {};o.o = o;// Note: cache should not be re-used by repeated calls to JSON.stringify.var cache = [];JSON.stringify(o, function(key, value) { if (typeof value === 'object' && value !== null) { if (cache.indexOf(value) !== -1) { // Duplicate reference found try { // If this value does not reference a parent it can be deduped return JSON.parse(JSON.stringify(value)); } catch (error) { // discard key if value cannot be deduped return; } } // Store value in our collection cache.push(value); } return value;});cache = null; // Enable garbage collection
最佳解决方案
var circularReference = {otherData: 123};circularReference.myself = circularReference;
wrong examples
JSON.stringify(circularReference);// TypeError: cyclic object value
要序列化循环引用,您可以使用支持它们的库(例如cycle.js)或自己实现解决方案,这需要通过可序列化的值查找和替换(或删除)循环引用。
const getCircularReplacer = () => { const seen = new WeakSet(); return (key, value) => { if (typeof value === "object" && value !== null) { if (seen.has(value)) { return; } seen.add(value); } return value; };};JSON.stringify(circularReference, getCircularReplacer());
参考: