likes
comments
collection
share

处理TypeError: Converting circular structure to JSON

作者站长头像
站长
· 阅读数 45

产生此错误的原因是因为对象中有对自身的循环引用


// Demo: Circular reference 
const o = {}; 
o.o = o;

// Note: cache should not be re-used by repeated calls to JSON.stringify. 

let cache = []; 

function stringifyCircularHandler(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;
};

JSON.stringify(req, stringifyCircularHandler);

reference:https://www.cnblogs.com/rubyl...