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
Release: 2024-12-17 16:10:10
Original
248 people have browsed it

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
Copy after login

Usage:

console.log(util.inspect(myObject));
Copy after login

Options:

util.inspect offers customization options via an options object:

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

Example:

Consider the following object with a circular reference:

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

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

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template