如何以类似 JSON 的格式打印圆形结构? [英] How can I print a circular structure in a JSON-like format?

查看:32
本文介绍了如何以类似 JSON 的格式打印圆形结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大对象要转换为 JSON 并发送.但是它具有圆形结构.我想丢弃任何存在的循环引用并发送任何可以字符串化的内容.我该怎么做?

I have a big object I want to convert to JSON and send. However it has circular structure. I want to toss whatever circular references exist and send whatever can be stringified. How do I do that?

谢谢.

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

我想将 obj 字符串化为:

I want to stringify obj into:

{"a":"foo"}

推荐答案

使用带有自定义替换器的 JSON.stringify.例如:

Use JSON.stringify with a custom replacer. For example:

// 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% 正确(取决于您对重复"的定义).在以下情况下,一个值将被丢弃:

The replacer in this example is not 100% correct (depending on your definition of "duplicate"). In the following case, a value is discarded:

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, ...);

但这个概念仍然存在:使用自定义替换器,并跟踪解析的对象值.

But the concept stands: Use a custom replacer, and keep track of the parsed object values.

作为用 es6 编写的实用函数:

As a utility function written in 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))

这篇关于如何以类似 JSON 的格式打印圆形结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆