JSON in JavaScript
Learning Focus
JSON is native to JavaScript — but JSON.parse and JSON.stringify have important edge cases that trip up even experienced developers.
Core Methods
// Deserialize
const raw = '{"name":"Alice","age":30,"active":true}';
const obj = JSON.parse(raw);
console.log(obj.name); // Alice
console.log(typeof obj.age); // number
// Serialize
const data = { name: "Bob", scores: [95, 87], active: true };
const compact = JSON.stringify(data);
const pretty = JSON.stringify(data, null, 2);
Reviver (Post-Parse)
const raw = '{"name":"Alice","createdAt":"2024-01-15T08:30:00Z"}';
const obj = JSON.parse(raw, (key, value) => {
if (key === "createdAt") return new Date(value);
return value;
});
console.log(obj.createdAt instanceof Date); // true
Replacer (Pre-Stringify)
const user = { id: 1, name: "Alice", password: "secret" };
// Only include id and name
const safe = JSON.stringify(user, ["id", "name"], 2);
Deep Clone Pattern
// JSON-safe objects only (no functions, dates, undefined, circular refs)
const clone = JSON.parse(JSON.stringify(original));
// Preferred (Node 17+, modern browsers)
const safeClone = structuredClone(original);
Fetch API with JSON
// GET
const user = await fetch(`/api/users/${id}`)
.then(r => { if (!r.ok) throw new Error(r.status); return r.json(); });
// POST
const created = await fetch("/api/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Alice" })
}).then(r => r.json());
Large Integer Precision
// ⚠️ Silent precision loss
JSON.parse('{"id": 9007199254740993}').id // 9007199254740992 — wrong!
// Fix: transmit large integers as strings
JSON.parse('{"id": "9007199254740993"}').id // "9007199254740993" — correct
Concept Map
Concept Flow
JSON String → JSON.parse → JS Object → Business Logic → JSON.stringify → JSON Output
Fetch API → response.json() → JS Object
Common Pitfalls
| Pitfall | Consequence | Prevention |
|---|---|---|
undefined values | Silently dropped from output | Use null instead |
| Functions in objects | Silently dropped | Never include functions in data objects |
| BigInt | TypeError: BigInt not serializable | .toString() before stringify |
| Circular references | TypeError: cyclic object value | Use flatted or sanitize manually |
What's Next
- Previous: JSON in Python — Review Python patterns.
- Next: JSON in Go — Strongly typed JSON with struct tags.
- Section Overview — Return to the Programming module index.