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.stringify turns JavaScript values into a string safe to send over the network or store; JSON.parse turns that string back into values — and both throw if misused, so Episode 1 code should try/catch around 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"}'
FeatureNotes
OutputAlways a string (or undefined for some values like undefined in arrays — edge case)
replacerArray of keys to keep, or function to filter/transform (advanced)
spacePretty-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
FeatureNotes
InputMust be valid JSON text — strict double quotes on keys/strings
OutputPlain objects and arrays of primitives — not your original class instances
reviverFunction 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

JavaScriptJSON
undefined (object property)Omitted (or null in arrays as null)
DateSerialized as string (ISO if you use date.toISOString() yourself) — parse does not auto-revive Dates
Map / Set / RegExpNot first-class — convert manually
FunctionsDropped or not allowed

6. Key takeaways

  1. stringify for storage and request bodies; parse for responses and stored strings.
  2. parse throws on bad JSON — guard with try/catch.
  3. JSON is data, not behavior — no functions round-trip.

Explain-It Challenge

Explain without notes:

  1. Why does JSON.stringify(document.body) usually fail?
  2. What is the difference between await res.json() and JSON.parse(await res.text()) for a JSON API?
  3. Why wrap JSON.parse(localStorage.getItem('x')) in try/catch in defensive code?

Navigation: ← 1.17.a — Throttle & Debounce · 1.17 Overview