Skip to main content

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

PitfallConsequencePrevention
undefined valuesSilently dropped from outputUse null instead
Functions in objectsSilently droppedNever include functions in data objects
BigIntTypeError: BigInt not serializable.toString() before stringify
Circular referencesTypeError: cyclic object valueUse flatted or sanitize manually

What's Next