← 中文资源

简体中文版本

JSON.stringify 拒绝循环引用

循环引用让 JSON.stringify 直接抛 TypeError,整次序列化失败;打日志时要么先断开环,要么用 replacer 把成环的键替换成占位文本,保住其余字段。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

error: true
safe: {"id":1,"next":"[linked]"}

实现说明

node、safe 定义在模块顶层,中间不经过函数作用域。 模块级对象字面量,键名固定:id、next。

使用要点

  • 每一步打印都带着自己的标签:error:、safe:。

常见问题

需要安装第三方包吗?

不需要。只使用语言和平台的内建 API,粘贴进项目即可使用,无需安装任何东西。 状态都挂在模块顶层:node、safe。

核心语句

const safe = JSON.stringify(node, (key, value) => (key === 'next' ? '[linked]' : value));
JSON.stringify(node);

代码示例

const node = { id: 1, next: null };
node.next = node; // linked-list style circular reference

// JSON.stringify throws a TypeError as soon as it hits a circular reference
try {
  JSON.stringify(node);
} catch (err) {
  console.log('error:', err instanceof TypeError);
}

// the logging path uses a replacer to skip the cycle-forming key instead of letting the whole serialization crash
const safe = JSON.stringify(node, (key, value) => (key === 'next' ? '[linked]' : value));
console.log('safe:', safe);