It's pretty certainly happened to every one of us at some point or another. Debugging our Node.js code, trying to surface some errors through our logs or observability tools, only to be hit by this:

TypeError: Converting circular structure to JSON
at JSON.stringify (<anonymous>)
at...
Oh, what a pain...

This means that the JSON we're trying to print contains references to itself or other parts of itself. Circular references. Like this:

const nestedObject = { prop1: "value" }
let circularObject: any = {};  
circularObject.prop1 = nestedObject;
circularObject.prop1.subprop1 = nestedObject;

Now, while some will suggest some custom replacers for dear JSON.stringify, looping through our objects to eliminate the culprit duplicate reference, I am a lazy one. A lazy one who stricly adheres by the following rule: The best code is the code we don't write (see Jeff Atwood's and Rich Skrenta's takes on the matter).

And it just so happens that Node.js' util module has something that already does the job well enough: inspect.

Here's how to use it:

import { inspect } from 'util'

const nestedObject = { prop1: "value" }
let circularObject: any = {};  
circularObject.prop1 = nestedObject;
circularObject.prop1.subprop1 = nestedObject;

console.log(inspect(circularObject))

Yes, that is it! Now you can happily debug your code, circular objects be damned.


Take aways

Three simple rules to remember:

monochrome wooden wagon
Unless you're in the wheels business. In which case, these two probably need some fixing - Photo by Jon Toney / Unsplash