迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

JavaScript 中 TypeError: Converting circular structure to JSON 错误

作者:迹忆客 最近更新:2023/01/20 浏览次数:

当我们将包含循环引用的对象传递给 JSON.stringify() 方法时,会发生“Converting circular structure to JSON”错误。

要解决该错误,需要确保在将对象转换为 JSON 之前删除所有循环引用。

下面是产生上述错误的一个示例

const obj = {};
obj.name = obj;

// ⛔️ TypeError: Converting circular structure to JSON
console.log(JSON.stringify(obj));

// -------------------------------------------------

const arr = [{}];
arr[0].arr = arr;

// ⛔️ TypeError: Converting circular structure to JSON
JSON.stringify(arr);

JavaScript 中 TypeError- Converting circular structure to JSON 错误

我们在对象上设置一个指向对象本身的属性——这是一个循环引用。

JSON.stringify 方法不支持循环引用,因此我们必须在将对象转换为 JSON 之前将其删除。

如果我们发现循环引用的位置,换句话说,对象中的值是对象本身,请在转换为 JSON 之前将其删除。

以下是一些需要注意的事项:

  • 确保从代码中删除与该对象相关的任何不必要的 console.log() 调用,因为它们也可能导致错误。
  • 错误的一个常见原因是忘记等待承诺。
  • 有些 API 会自动调用 JSON.stringify(),因此我们不必这样做,例如 res.json(obj)。 我们不必使用 obj 调用 JSON.stringify(),因为 res.json() 方法会自动为我们完成。

尝试删除对 JSON.stringify() 的调用并查看您的代码是否有效(某些 API 可能正在为我们调用该方法)。

或者,我们可以使用函数从对象中删除所有循环引用。

使用方法从对象中删除所有循环引用

下面是一个如何从对象中删除循环引用的示例。

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;
  };
};

const obj = {address: {country: 'Chile'}, numbers: [1, 2, 3], age: 30};
obj.name = obj;

// ✅ Works
const result = JSON.stringify(obj, getCircularReplacer());
console.log(result); // 👉️ {"address":{"country":"Chile"},"numbers":[1,2,3],"age":30}

我们将调用 getCircularReplacer 函数的结果作为第二个参数传递给 JSON.stringify() 方法。

第二个参数使我们能够控制哪些值被字符串化,哪些不被字符串化。

该函数从对象中删除任何循环引用,因此在将它传递给 JSON.stringify() 方法时我们不会收到错误。

或者,我们可以使用 flatted 包 - 一个轻便快速的循环 JSON 解析器。


使用扁平包解决循环引用

首先,在项目的根目录中打开终端以安装包。

# 👇️ with NPM
$ npm install flatted

# 👇️ with YARN
$ yarn add flatted

现在我们可以使用 flatted 包中的 stringify() 方法。

import {parse, stringify, toJSON, fromJSON} from 'flatted';

const arr = [{}];
arr[0].arr = arr;
arr.push(arr);

const result = stringify(arr); // [["1","0"],{"a":"0"}]

console.log(result); // 👉️ [["1","0"],{"arr":"0"}]

代码示例使用 ES6 导入/导出语法,如果我们使用 require(),请更新我们的导入语句。

// 👇️ using CJS (require())
const {parse, stringify, toJSON, fromJSON} = require('flatted');

const arr = [{}];
arr[0].arr = arr;
arr.push(arr);

const result = stringify(arr); // [["1","0"],{"a":"0"}]

console.log(result); // 👉️ [["1","0"],{"arr":"0"}]

我们可以在包的 NPM 页面中阅读有关如何使用扁平化包的更多信息。


总结

当我们将包含循环引用的对象传递给 JSON.stringify() 方法时,会发生“Converting circular structure to JSON”错误。

要解决该错误,需要确保在将对象转换为 JSON 之前删除所有循环引用。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

JavaScript POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便