JavaScript JSON Limits: Cycles and Lost Types
Quick answer
JSON describes a tree of data, not arbitrary graphs of JavaScript identities. Cycles, shared references and specialized types require an explicit encoding policy.
How it works
A self-reference causes ordinary JSON.stringify to throw TypeError. Shared noncyclic objects can be encoded twice, losing shared identity after parsing. Map and Set entries are not ordinary enumerable properties, so serializing an unmodified instance typically yields {}. Convert them to an agreed array representation when needed. Date generally serializes an ISO timestamp string, not a Date object.
const x={}; x.self=x; try{JSON.stringify(x);}catch(e){console.log(e.name);}Expected output in Node.js:
TypeErrorCycles are rejected by ordinary JSON serialization.
const x={n:1}; const y=JSON.parse(JSON.stringify({a:x,b:x})); console.log(y.a.n,y.a===y.b,JSON.stringify(new Map([["a",1]])));Expected output in Node.js:
1 false {}Shared identity and Map entry structure are lost.
Common mistakes
Do not use a JSON round trip to clone an arbitrary application graph or persist types without a documented format.
Practice
Write a serialization contract for a map of string IDs to quantities, and explain how a decoder restores it.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript JSON Limits: Cycles and Lost Types — Knowledge Check
Apply the taught concept and predict the output.
What does ordinary JSON.stringify do on a circular object graph?
How can a Map with string keys be represented in a JSON contract?
What happens to shared noncyclic object identity after a normal JSON round trip?
What is the exact console output in JavaScript JSON Limits: Cycles and Lost Types example 1?
const x={}; x.self=x; try{JSON.stringify(x);}catch(e){console.log(e.name);}What is the exact console output in JavaScript JSON Limits: Cycles and Lost Types example 2?
const x={n:1}; const y=JSON.parse(JSON.stringify({a:x,b:x})); console.log(y.a.n,y.a===y.b,JSON.stringify(new Map([["a",1]])));