Episode 1 — Fundamentals / 1.17 — Additional JavaScript Topics
1.17.b — JSON Handling: JSON.parse() & JSON.stringify() (Episode 1)
In one sentence: JSON is a text format for data —
JSON.stringifyturns JavaScript values into a string safe to send over the network or store;JSON.parseturns that string back into values — and both throw if misused, so Episode 1 code shouldtry/catcharound untrusted text.
Navigation: ← 1.17.a — Throttle & Debounce · 1.17 Overview
1. What is JSON?
JSON (JavaScript Object Notation) is a subset of object/array literal syntax: objects { "key": value }, arrays [1,2], strings in double quotes, true/false/null, and numbers — no undefined, no functions, no BigInt in standard JSON, no comments.
It is the lingua franca for REST APIs and fits fetch bodies and localStorage values (see 1.16).
2. JSON.stringify(value[, replacer[, space]])
const user = { name: "Ada", role: "dev" };
JSON.stringify(user);
// '{"name":"Ada","role":"dev"}'
| Feature | Notes |
|---|---|
| Output | Always a string (or undefined for some values like undefined in arrays — edge case) |
replacer | Array of keys to keep, or function to filter/transform (advanced) |
space | Pretty-print indent (debugging / logs) |
Circular references (object a references b references a) throw — common pitfall with DOM nodes or rich graphs.
JSON.stringify({ x: 1 }, null, 2); // indented for readability
3. JSON.parse(text[, reviver])
const text = '{"count":3,"ok":true}';
const data = JSON.parse(text);
data.count; // 3
| Feature | Notes |
|---|---|
| Input | Must be valid JSON text — strict double quotes on keys/strings |
| Output | Plain objects and arrays of primitives — not your original class instances |
reviver | Function to post-process keys/values while building (advanced) |
Invalid JSON throws SyntaxError:
try {
JSON.parse("{ not json }");
} catch (e) {
console.error("Bad JSON", e);
}
4. Episode 1 patterns
With fetch
const res = await fetch("/api/item");
if (!res.ok) throw new Error(String(res.status));
const data = await res.json(); // built-in; parses JSON body
response.json() is JSON.parse under the hood on the body string — same rules apply.
With localStorage
const prefs = { theme: "dark", size: 14 };
localStorage.setItem("prefs", JSON.stringify(prefs));
const raw = localStorage.getItem("prefs");
const restored = raw ? JSON.parse(raw) : { theme: "light", size: 16 };
Always parse inside try/catch if data might be corrupt or tampered.
5. What JSON cannot represent
| JavaScript | JSON |
|---|---|
undefined (object property) | Omitted (or null in arrays as null) |
Date | Serialized as string (ISO if you use date.toISOString() yourself) — parse does not auto-revive Dates |
Map / Set / RegExp | Not first-class — convert manually |
| Functions | Dropped or not allowed |
6. Key takeaways
stringifyfor storage and request bodies;parsefor responses and stored strings.parsethrows on bad JSON — guard withtry/catch.- JSON is data, not behavior — no functions round-trip.
Explain-It Challenge
Explain without notes:
- Why does
JSON.stringify(document.body)usually fail? - What is the difference between
await res.json()andJSON.parse(await res.text())for a JSON API? - Why wrap
JSON.parse(localStorage.getItem('x'))intry/catchin defensive code?
Navigation: ← 1.17.a — Throttle & Debounce · 1.17 Overview