Lotus@ 2012-07-23 16:30 采纳率: 100%
浏览 755
已采纳

Stringfy,避免类型错误: 将循环结构转换为 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?

Thanks.

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

I want to stringify obj into:

{"a":"foo"}

转载于:https://stackoverflow.com/questions/11616630/json-stringify-avoid-typeerror-converting-circular-structure-to-json

  • 写回答

19条回答 默认 最新

  • 狐狸.fox 2012-07-23 16:56
    关注

    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
    

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(18条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记