处理TypeError: Converting circular structure to JSON

Posted Jun 27, 20201 min read

The reason for this error is because there is a circular reference to itself in the object

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