温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - How can I print a circular structure in a JSON-like format?
javascript json node.js

javascript - 如何以类似JSON的格式打印圆形结构?

发布于 2020-03-29 21:53:06

我有一个大对象,想要转换为JSON并发送。但是它具有圆形结构。我想扔掉任何存在的循环引用并发送任何可以字符串化的东西。我怎么做?

谢谢。

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

我想将obj字符串化为:

{"a":"foo"}

查看更多

提问者
Harry
被浏览
18
16.4k 2019-10-28 21:47

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, function(key, value) {
    if (typeof value === 'object' && value !== null) {
        if (cache.indexOf(value) !== -1) {
            // Duplicate reference found, discard key
            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, ...);

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