TypeError: cyclic object value
当在 JSON 中发现对象引用时,会发生 JavaScript 异常 "cyclic object value"。 JSON.stringify() 不会尝试解决它们,并因此失败。
消息
TypeError: Converting circular structure to JSON (V8-based) TypeError: cyclic object value (Firefox) TypeError: JSON.stringify cannot serialize cyclic structures. (Safari)
错误类型
TypeError
哪里出错了?
JSON 格式本身不支持对象引用(尽管存在 IETF 草案),因此 JSON.stringify() 不会尝试解决它们,并因此失败。
示例
循环引用
在以下循环结构中
js
const circularReference = { otherData: 123 };
circularReference.myself = circularReference;
JSON.stringify() 将失败
js
JSON.stringify(circularReference);
// TypeError: cyclic object value
要序列化循环引用,可以使用支持它们的库(例如,cycle.js),或者自己实现一个解决方案,这需要通过可序列化值查找和替换(或删除)循环引用。
下面的代码片段演示了如何使用 JSON.stringify() 的 replacer 参数查找和过滤(从而导致数据丢失)循环引用。
js
function getCircularReplacer() {
const ancestors = [];
return function (key, value) {
if (typeof value !== "object" || value === null) {
return value;
}
// `this` is the object that value is contained in,
// i.e., its direct parent.
while (ancestors.length > 0 && ancestors.at(-1) !== this) {
ancestors.pop();
}
if (ancestors.includes(value)) {
return "[Circular]";
}
ancestors.push(value);
return value;
};
}
JSON.stringify(circularReference, getCircularReplacer());
// {"otherData":123,"myself":"[Circular]"}
const o = {};
const notCircularReference = [o, o];
JSON.stringify(notCircularReference, getCircularReplacer());
// [{},{}]
另见
JSON.stringify()- cycle.js 在 GitHub 上