JSON.Stringify() Circular Reference
Troubleshooting JavaScript and TypeScript can often mean a lot of console.log
statements, or logging out to your chosen log aggrigator (I'm looking at you, New Relic ;)
). At times, getting a dump of a detailed object is beneficial, which is where JSON.Stringify()
comes in... however, since JavaScript objects are able to develop hierarchies by passing references as properties, those hierarchies can contain circular references.
To circumvent having a circular reference error thrown, we can implement a quick utility function. Here's some sample code that for that, note that the res
object we're using here is NOT and adequate offender for this test, so please substitute your own offending object with this utility function.
Code
const res = { circularObject: true }; // no, it isn't
console.log(${JSON.stringify(res, getCircularReplacer())});
function getCircularReplacer() {
const seen = new WeakSet();
// @ts-ignore
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
};