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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github