我有一个大对象,我想转换成JSON并发送.然而,它具有圆形 struct .我想扔掉任何循环引用,并发送任何可以字符串化的内容.我该怎么做?

谢谢

var obj = {
  a: "foo",
  b: obj
}

我想把obj严格化为:

{"a":"foo"}

推荐答案

JSON.stringify与自定义替换项一起使用.例如:

// Demo: Circular reference
var circ = {};
circ.circ = circ;

// Note: cache should not be re-used by repeated calls to JSON.stringify.
var cache = [];
JSON.stringify(circ, (key, value) => {
  if (typeof value === 'object' && value !== null) {
    // Duplicate reference found, discard key
    if (cache.includes(value)) return;

    // Store value in our collection
    cache.push(value);
  }
  return value;
});
cache = null; // Enable garbage collection

本例中的替换项不是100%正确(取决于"重复"的定义).在以下情况下,将丢弃一个值:

var a = {b:1}
var o = {};
o.one = a;
o.two = a;
// one and two point to the same object, but two is discarded:
JSON.stringify(o, ...);

但概念是:使用自定义替换程序,并跟踪解析的对象值.

作为用ES6编写的实用程序函数:

// safely handles circular references
JSON.safeStringify = (obj, indent = 2) => {
  let cache = [];
  const retVal = JSON.stringify(
    obj,
    (key, value) =>
      typeof value === "object" && value !== null
        ? cache.includes(value)
          ? undefined // Duplicate reference found, discard key
          : cache.push(value) && value // Store value in our collection
        : value,
    indent
  );
  cache = null;
  return retVal;
};

// Example:
console.log('options', JSON.safeStringify(options))

Javascript相关问答推荐

JavaScript:循环访问不断变化的数组中的元素

是什么原因导致此Angular 16电影应用程序中因类型错误而不存在属性?

如何在表格上拥有水平滚动条,在正文页面上拥有垂直滚动条,同时还对html表格的标题使用位置粘性?

fs. writeFile()vs fs.writeFile()vs fs.appendFile()

在我的html表单中的用户输入没有被传送到我的google表单中

我在我的Java代码中遇到了问题,代码的一部分看不到先前定义的对象

在react JS中映射数组对象的嵌套数据

Next.js服务器端组件请求,如何发送我的cookie token?

为什么我的getAsFile()方法返回空?

400 bad request error posting through node-fetch

在不删除代码的情况下禁用Java弹出功能WordPress

如果没有页面重新加载Angular ,innerHTML属性绑定不会更新

按什么顺序接收`storage`事件?

将范围 Select 器添加到HighChart面积图

Socket.IO在刷新页面时执行函数两次

如何在尚未创建的鼠标悬停事件上访问和着色div?

为什么我不能使用其同级元素调用和更新子元素?

未找到用于 Select 器的元素:in( puppeteer 师错误)

JQuery使用选项填充HTMLSELECT并设置默认结果,默认结果显示为空

如何在加载页面时使锚定标记成为焦点