Home >Web Front-end >JS Tutorial >How to Solve the 'TypeError: Converting circular structure to JSON' Error?

How to Solve the 'TypeError: Converting circular structure to JSON' Error?

Barbara Streisand
Barbara StreisandOriginal
2024-12-17 16:10:10299browse

How to Solve the

How to Convert Circular Structures to JSON-Compatible Formats

Encountering the "TypeError: Converting circular structure to JSON" error when attempting to stringify an object with circular references can be frustrating. Here's how you can handle this issue:

In Node.js, utilizing the built-in util.inspect module provides a convenient solution. It automatically replaces circular references with "[Circular]".

Importing the Module:

import * as util from 'util'; // for NodeJS modules
import { inspect } from 'util'; // for ES modules
var util = require('util'); // for CommonJS modules

Usage:

console.log(util.inspect(myObject));

Options:

util.inspect offers customization options via an options object:

inspect(myObject[, options: {
  showHidden,
  depth,
  colors,
  showProxy,
  ...moreOptions}])

Example:

Consider the following object with a circular reference:

var obj = {
  a: "foo",
  b: obj,
};

Using util.inspect, you can obtain the JSON-compatible representation:

console.log(util.inspect(obj));
// Output: {"a":"foo","b":"[Circular]"}

Additional Notes:

  • Refer to the documentation for util.inspect for further options and details.
  • Express your appreciation to the insightful commenters below for their contributions.

The above is the detailed content of How to Solve the 'TypeError: Converting circular structure to JSON' Error?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn