JSON & Data
JSON is a text format for exchanging data, not a subset of JavaScript, even though the syntax looks similar. Hence the main idea of the topic — serializing to JSON loses everything the format has no place for: undefined, functions, symbols, dates, Map/Set, and it throws outright on cycles and BigInt. Understanding exactly what is lost matters more than remembering the signatures.
Everything else is built around two functions — JSON.stringify and JSON.parse: their replacer/reviver arguments give control over transformation, the JSON round-trip gives a quick (but lossy) deep clone, and eval is the deprecated and dangerous way to "revive" text that you should avoid. The full map lives in the layers below.
Topic map
- JSON basics — what JSON is, which types it allows, and what cannot be in it.
- Serialization —
JSON.stringify,replacer,toJSON, indentation, and what is silently dropped. - Parsing —
JSON.parse,reviver, andSyntaxErroron invalid input. - Deep cloning — the JSON round-trip versus
structuredCloneand a manual clone. - The dangers of eval — why
evalis dangerous and what to use instead.
Common traps
| Mistake | Consequence |
|---|---|
Expecting stringify to keep functions and undefined | In an object such keys are dropped, in an array they become null |
| Serializing an object with a cycle | JSON.stringify throws a TypeError |
Serializing a BigInt | Also a TypeError — JSON has no type for it |
Cloning via JSON and expecting Date/Map to survive | Date becomes a string, Map/Set become an empty {} |
Assuming JSON.parse is safe on any input | Invalid JSON throws a SyntaxError — you need try/catch |
Using eval to parse data | Code injection and lost optimizations — use JSON.parse instead |
Interview relevance
JSON is asked as a check of whether you understand the difference between a value in memory and its text representation, and whether you know the format's concrete losses. A candidate who lists exactly what JSON.parse(JSON.stringify(x)) loses — functions, undefined, Date, cycles — immediately shows depth.
Typical checks:
- Which types JSON cannot represent and how each one "breaks".
- What
JSON.stringifydoes with a function,undefined,NaN,Infinity. - How the JSON clone works and what its pitfalls are.
- Why
evalis dangerous and what to use instead.
Common wrong answer: "JSON.parse(JSON.stringify(obj)) is a perfect deep clone". No — it loses functions and undefined, corrupts Date and Map, and throws on cycles and BigInt; for an honest clone there is structuredClone.