Loading...
Loading...
TypeError: Converting circular structure to JSONJSON.stringify() cannot serialize objects that reference themselves (circular references). For example, if object A has a property pointing to object B, and object B has a property pointing back to A, JSON.stringify() will loop forever and throw this error.
Pass a custom replacer to JSON.stringify() that tracks seen objects.
function safeStringify(obj) {
const seen = new WeakSet();
return JSON.stringify(obj, (key, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) return '[Circular]';
seen.add(value);
}
return value;
});
}Install the npm package for a drop-in safe replacement.
npm install json-stringify-safe
const stringify = require('json-stringify-safe');
console.log(stringify(obj));