How Can I Print a Circular Structure in a Json-like Format?

Better Stack Team
Updated on April 4, 2024

If you have an object with circular references in Node.js and you want to print it in a JSON-like format, you can use the util.inspect method from the built-in util module. The util.inspect method provides options to handle circular references and format the output.

Here's an example:

 
const util = require('util');

const circularObject = {
  prop1: 'value1',
  prop2: {
    prop3: 'value3',
  },
};

// Create a circular reference
circularObject.circularRef = circularObject;

// Use util.inspect to print the object with circular references
const formattedOutput = util.inspect(circularObject, { depth: null });
console.log(formattedOutput);

In this example:

  • The util.inspect method is used to print the object with circular references.
  • The depth: null option allows inspecting objects with circular references by setting the depth to null (unlimited depth).
  • The result is a formatted string that represents the object with circular references in a JSON-like format.

Adjust the options of util.inspect according to your needs. The util.inspect method is powerful and provides various options for formatting and customizing the output. Refer to the official documentation for more details on available options.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.