When attempting to serialize circular structures in JavaScript using JSON.stringify(), errors like "Converting circular structure to JSON" or "TypeError: cyclic object value" arise. To address this, it's necessary to eliminate circular references.
Node.js provides a built-in solution: util.inspect().
Import it:
import * as util from 'util'; // or import { inspect } from 'util'; // or var util = require('util');
Usage:
console.log(util.inspect(myObject));
util.inspect() replaces circular links with "[Circular]". It also accepts an options object for customization.
Sample Output:
{ a: 'foo', b: '[Circular]' }
The above is the detailed content of How Can I Handle Circular Structures When JSONifying in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!