DEV Community

Fedor
Fedor

Posted on

2

How to fix Converting circular structure to JSON

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))

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Some comments have been hidden by the post's author - find out more

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay