Stringify Circular JSON

JavaScriptJavaScriptBeginner
Practice Now

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/NetworkingGroup(["`Networking`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/cond_stmts("`Conditional Statements`") javascript/BasicConceptsGroup -.-> javascript/obj_manip("`Object Manipulation`") javascript/AdvancedConceptsGroup -.-> javascript/destr_assign("`Destructuring Assignment`") javascript/NetworkingGroup -.-> javascript/json("`JSON`") subgraph Lab Skills javascript/variables -.-> lab-28629{{"`Stringify Circular JSON`"}} javascript/data_types -.-> lab-28629{{"`Stringify Circular JSON`"}} javascript/arith_ops -.-> lab-28629{{"`Stringify Circular JSON`"}} javascript/comp_ops -.-> lab-28629{{"`Stringify Circular JSON`"}} javascript/cond_stmts -.-> lab-28629{{"`Stringify Circular JSON`"}} javascript/obj_manip -.-> lab-28629{{"`Stringify Circular JSON`"}} javascript/destr_assign -.-> lab-28629{{"`Stringify Circular JSON`"}} javascript/json -.-> lab-28629{{"`Stringify Circular JSON`"}} end

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.

Other JavaScript Tutorials you may like