Stringify Circular JSON

Beginner

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will be exploring how to serialize a JSON object that contains circular references using JavaScript. We will use a custom replacer function and a WeakSet to detect and omit circular references. By the end of this lab, you will have a better understanding of how to handle circular data structures in JavaScript and how to serialize them into JSON format.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 100% completion rate. It has received a 100% positive review rate from learners.

How to Stringify Circular JSON

To stringify a JSON object that contains circular references, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Create a WeakSet to store and check seen values using WeakSet.prototype.add() and WeakSet.prototype.has().
  3. Use JSON.stringify() with a custom replacer function that omits values already in seen, and adds new values if necessary.
  4. ⚠️ NOTICE: This function finds and removes circular references, which causes circular data loss in the serialized JSON.

Here's the code for the stringifyCircularJSON function:

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

To test the function, you can create an object with a circular reference and call stringifyCircularJSON:

const obj = { n: 42 };
obj.obj = obj;
stringifyCircularJSON(obj); // '{"n": 42}'

Summary

Congratulations! You have completed the Stringify Circular JSON lab. You can practice more labs in LabEx to improve your skills.