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:
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!