bug^君 2012-07-23 16:30 采纳率: 25%
浏览 814
已采纳

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条回答 默认 最新

  • ?yb? 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 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题