将循环结构转换为JSON

将循环结构转换为JSON

本文介绍了JSON.stringify,避免TypeError:将循环结构转换为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 o = {};
o.o = o;

// Note: cache should not be re-used by repeated calls to JSON.stringify.
var cache = [];
JSON.stringify(o, function(key, value) {
    if (typeof value === 'object' && value !== null) {
        if (cache.indexOf(value) !== -1) {
            // Duplicate reference found
            try {
                // If this value does not reference a parent it can be deduped
                return JSON.parse(JSON.stringify(value));
            } catch (error) {
                // discard key if value cannot be deduped
                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.stringify,避免TypeError:将循环结构转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 02:48