MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Circular Reference Handling & Custom Serialization0%
Study Materials
JavaScript for AdvancedProgress 0%
1.1Higher-Order Functions & Currying1.2Function Composition & Pipelining1.3Memoization & Pure Functions1.4Execution Context & Call Stack Deep Dive1.5Scope Chain & Lexical Environment
12.1JSON.stringify Replacer & JSON.parse Reviver12.2Circular Reference Handling & Custom Serialization12.3JSON Schema Validation12.4Streaming JSON & NDJSON
HomeTutorialsJavaScript for AdvancedCircular Reference Handling & Custom Serialization
JSON Schema Validation

Circular Reference Handling & Custom Serialization

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study Materials

A frequent crash in web applications occurs when attempting to serialize complex domain models, DOM nodes, or graph data structures: TypeError: Converting circular structure to JSON. Understanding how to detect, prune, and serialize cyclic object graphs is essential for enterprise data pipelines.


1. What is a Circular Reference?

A circular reference occurs when an object references itself directly or indirectly through a chain of properties:

1const person = { name: 'Alice' };
2const club = { name: 'Chess Club', president: person };
3person.club = club; // CIRCULAR REFERENCE! (person -> club -> person -> club...)
4 
5// JSON.stringify(person);
6// Uncaught TypeError: Converting circular structure to JSON

2. Solution 1: Cycle-Detecting Replacer using WeakSet

A lightweight solution tracks visited objects using a WeakSet:

1function getCircularReplacer() {
2 const seen = new WeakSet();
3 
4 return (key, value) => {
5 // If value is an object, check if already visited
6 if (typeof value === 'object' && value !== null) {
7 if (seen.has(value)) {
8 return '[Circular Reference]'; // Replace cycle with marker string
9 }
10 seen.add(value);
11 }
12 return value;
13 };
14}
15 
16const safeJson = JSON.stringify(person, getCircularReplacer(), 2);
17console.log(safeJson);
18// {
19// "name": "Alice",
20// "club": {
21// "name": "Chess Club",
22// "president": "[Circular Reference]"
23// }
24// }

3. Solution 2: Custom Serialization with toJSON()

If an object implements a toJSON() method, JSON.stringify automatically calls that method instead of inspecting the object's raw properties:

1class TreeNode {
2 constructor(value) {
3 this.value = value;
4 this.parent = null;
5 this.children = [];
6 }
7 
8 addChild(childNode) {
9 childNode.parent = this; // Creates circular link!
10 this.children.push(childNode);
11 }
12 
13 // Custom serialization overrides default stringifier!
14 toJSON() {
15 return {
16 value: this.value,
17 // Omit 'parent' to eliminate the circular reference!
18 children: this.children
19 };
20 }
21}
22 
23const root = new TreeNode('Root');
24const child = new TreeNode('Child 1');
25root.addChild(child);
26 
27console.log(JSON.stringify(root, null, 2)); // Serializes cleanly without circular crash!

4. Graph Serialization (Flatted / Reference IDs)

When you need to preserve the exact relational graph so it can be reconstructed on the server, assign unique reference IDs:

1function serializeGraph(root) {
2 const objectMap = new Map();
3 let idCounter = 1;
4 
5 function buildGraph(obj) {
6 if (!obj || typeof obj !== 'object') return obj;
7 if (objectMap.has(obj)) {
8 return { $ref: objectMap.get(obj) }; // Reference existing ID
9 }
10 
11 const id = `id_${idCounter++}`;
12 objectMap.set(obj, id);
13 
14 const serialized = Array.isArray(obj) ? [] : { $id: id };
15 for (const [key, val] of Object.entries(obj)) {
16 serialized[key] = buildGraph(val);
17 }
18 return serialized;
19 }
20 
21 return JSON.stringify(buildGraph(root));
22}

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What runtime error is thrown when JSON.stringify() encounters an object that references itself?
Question 2
How does a WeakSet assist in handling circular references during JSON.stringify()?
Question 3
What method can be added to an object or class to customize its output during JSON.stringify()?
Question 4
Why is WeakSet preferred over Array or Set for tracking visited objects in a serialization replacer?
Question 5
If person.club.president points back to person, what is this relationship called?
Next Lesson

JSON Schema Validation

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
JSON.stringify Replacer & JSON.parse ReviverJSON Schema Validation

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext