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

查看:98
本文介绍了如何以类似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分为:

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

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.

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

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