JSON.stringify "Converting circular structure to JSON"问题

杨天栾

2018-08-09

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

第76篇《JSON.stringify "Converting circular structure to JSON"问题》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
杨天栾 2018.08.09
对象中有循环引用

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android