处理TypeError: Converting circular structure to JSON

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


// 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...

你可能感兴趣的:(javascript,node.js,json,json.stringify)