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.
How to Stringify Circular JSON
To stringify a JSON object that contains circular references, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Create a
WeakSetto store and check seen values usingWeakSet.prototype.add()andWeakSet.prototype.has(). - Use
JSON.stringify()with a custom replacer function that omits values already inseen, and adds new values if necessary. - ⚠️ 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.