Advertisement
Advanced JavaScript, JSON & Data Serialization

Why does JSON.stringify() throw a TypeError on objects with circular references, and how do you handle it?

Short answer

JSON has no concept of references, so stringify would need to serialize the same nested structure infinitely if an object refers back to itself (directly or indirectly) — the engine detects this and throws rather than looping forever.

Save JavaScript mock interview
Advertisement
AModel answer
JSON has no concept of references, so stringify would need to serialize the same nested structure infinitely if an object refers back to itself (directly or indirectly) — the engine detects this and throws rather than looping forever. You can fix it by tracking visited objects yourself in a custom replacer, or using structuredClone for cloning instead.
const obj = {};
obj.self = obj; // circular reference
JSON.stringify(obj); // TypeError: Converting circular structure to JSON
Real-world example
A bug where serializing a DOM node or a Vue/React internal object accidentally includes a circular parent reference.
Likely follow-ups
  • How does structuredClone() differ from JSON.stringify/parse for cloning, especially with circular references?
Related topics