How to fix Converting circular structure to JSON

Fedor - Dec 16 '22 - - Dev Community

Oftentimes while fine-tuning building process you need to output lots of data.

Common case scenario is when you track the process of SplitChunksPlugin in Webpack and you want to see what module goes in what place, whats in the module, in what chunks it was required etc.
So you use
const data = { module, ...chunks };
fs.writeFileSync('report', JSON.stringify(data))

This will emit error

"Converting circular structure to JSON"

thats bc module is has nesting and cross-references on itself in its structure.

JSON.stringify can accept 3 arguments, 1st is data 2nd is a replacer and 3d is a spacer for formatting stuff.

So there a function to avoid error, this function should be used as a replacer.

const getCircularReplacer = () => {
  const seen = new WeakSet();
  return (key, value) => {
    if (typeof value === "object" && value !== null) {
      if (seen.has(value)) {
        return;
      }
      seen.add(value);
    }
    return value;
  };
};

Enter fullscreen mode Exit fullscreen mode

And this will work:
fs.writeFileSync('report', JSON.stringify(data, getCircularReplacer(), 2))

. . . . . . . . . . . . . . . . . .
Terabox Video Player