JSON.stringify出现 "Converting circular structure to JSON"

JSON.stringify()  我们很熟悉了,将一个对象转换为json形式的字符串. 

但是如果你在浏览器控制台中输出 JSON.stringify(window). 如果期望输出一段文字, 可能会失望了. 事实上, 会输出结果如下:

错误信息很明显了, 对象中有循环引用. 解决方案如下:

参考链接:http://stackoverflow.com/questions/11616630/json-stringify-avoid-typeerror-converting-circular-structure-to-json

// 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) {
            // Circular reference found, discard key
            return;
        }
        // Store value in our collection
        cache.push(value);
    }
    return value;
});
cache = null; // Enable garbage collection

JSON.stringify说明  https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

至于出现循环引用的原因,参考如下:

原文链接:

http://stackoverflow.com/questions/4816099/chrome-sendrequest-error-typeerror-converting-circular-structure-to-json

原文地址:https://www.cnblogs.com/dfyg-xiaoxiao/p/6810491.html