JSON and Serialization
Turning a value into a JSON string and back with `JSON.stringify`/`parse`, their `replacer`/`reviver` hooks, and what gets lost on the way through.
JSON and Serialization
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- `JSON.stringify(value)` turns a JavaScript value into a JSON-formatted string; `JSON.parse(str)` turns a JSON string back into a JavaScript value — this is how objects survive being sent over a network or saved to disk, since both only ever deal in bytes and text, never live objects.
- `stringify`'s second argument, the replacer, controls what gets included — pass an array of allowed keys to filter the output, or a function to transform or drop values as they're serialized.
- `parse`'s second argument, the reviver, runs on every key/value pair as the string is parsed — the usual use is turning a date string back into an actual `Date`, since JSON itself has no date type.
- `JSON.stringify` silently drops functions, `undefined` values, and symbols rather than erroring — they just vanish from the output, which is a common source of "why isn't this field in my JSON" confusion.
- A circular reference — an object that points back to itself, directly or through a chain — makes `JSON.stringify` throw, because JSON has no way to represent a structure that loops back on itself.
The problem: objects don’t survive leaving the process
A JavaScript object is a live thing — it exists in memory, with references
to other objects, maybe methods attached to it. The moment you need to send
that object somewhere else — across a network to a server, into a file on
disk, into localStorage — none of those destinations understand “a live
JavaScript object.” They understand bytes and text. Something has to
flatten the object into a format any system can read, and reconstruct it on
the other end.
JSON (JavaScript Object Notation) is that format: a small, strict text
syntax for representing objects, arrays, strings, numbers, booleans, and
null. JSON.stringify does the flattening; JSON.parse does the
reconstruction. This is the single most common way structured data crosses
any boundary in a JS program — API responses, config files, saved
application state — so it’s worth knowing exactly what the round trip
does and doesn’t preserve.
The basic round trip
const user = { name: "Ada", age: 31, active: true };
const text = JSON.stringify(user);
// '{"name":"Ada","age":31,"active":true}'
const restored = JSON.parse(text);
// { name: "Ada", age: 31, active: true } — a new object, equal in content
restored is a brand-new object — restored === user is false. The round
trip rebuilds an equivalent value from scratch; it doesn’t hand back the
original.
Controlling the output and the input
Both functions take an optional second argument that hooks into the
process. stringify’s replacer controls what goes out:
JSON.stringify(user, ["name", "age"]);
// '{"name":"Ada","age":31}' — only the listed keys survive
JSON.stringify(user, (key, value) =>
typeof value === "number" ? value * 2 : value
);
// numbers get transformed as they're serialized
parse’s reviver runs as values come back in, which is exactly how
you’d restore something JSON itself can’t represent — a Date is the
textbook case, since it gets serialized as a plain ISO string and has no way
to know it should become a Date object again unless you tell it to:
JSON.parse(text, (key, value) =>
key === "createdAt" ? new Date(value) : value
);
What doesn’t make it through
JSON.stringify doesn’t error on things it can’t represent — it just drops
them, quietly. Functions, undefined values, and symbols all vanish from
the output without a warning, which is exactly the kind of thing that looks
like a bug until you know to expect it. The video covers this same ground —
stringify, parse, and the shape of what actually ends up in the string — and
is a good place to watch the replacer argument and the “things that vanish”
behavior happen live rather than taking it on faith.
The one case that doesn’t vanish quietly is a circular reference — an object that, through some chain of properties, eventually points back to itself:
const a = {};
a.self = a;
JSON.stringify(a); // throws: Converting circular structure to JSON
JSON is a flat, finite format with no notion of “this is the same object we
already started writing above it” — there’s no way to flatten a loop, so
stringify throws instead of trying.
Where this fits
This lesson leans on how objects and their properties actually work, which
is why it sits right after that group. From here, JSON is the format you’ll
see again constantly — every time this roadmap’s later async-and-fetch
material (in frontend) talks to a server, JSON is what’s actually crossing
the wire, and knowing exactly what the serialization step keeps and drops
will save you from some genuinely confusing bugs later.
Check yourself
Why can't you just send a JavaScript object directly over a network request or save it straight to a file?
A network connection or a file only deals in bytes and text — it has no concept of a live JavaScript object with methods, prototypes, and references. `JSON.stringify` converts the object into a plain text representation that any system can transmit or store, and `JSON.parse` reconstructs an equivalent object on the other end.
You `JSON.stringify` an object that has a method on it, a property set to `undefined`, and a property set to `42`. What shows up in the resulting string?
Only the property set to `42`. Methods (functions) and `undefined` values are silently omitted from the output — `JSON.stringify` doesn't error or warn, it just leaves them out, because JSON as a format has no way to represent a function or the concept of `undefined`.
What's the replacer argument to `JSON.stringify` for, and what are the two forms it can take?
It controls which parts of the value actually make it into the output. As an array of strings, it's an allow-list of keys to keep. As a function, it's called for every key/value pair and can transform a value or return `undefined` to drop that key from the output entirely.
You parse a JSON string back into an object, but a field that was a `Date` in the original object is now just a string. Why, and how would you fix it?
JSON has no native date type — `JSON.stringify` already converted that `Date` into an ISO string before it ever became JSON text, so `JSON.parse` has no way to know it should be a `Date` again on its own. Pass a reviver function as `JSON.parse`'s second argument to check for that specific key and convert the string back into a `new Date(...)` as the data is parsed.
Why does `JSON.stringify` throw an error on an object with a circular reference, instead of just serializing it somehow?
A circular reference means the object (directly or through a chain of other objects) points back to itself. JSON is a flat, finite text format with no way to express "and this part is the same thing we already wrote above" — stringify would have to write forever to flatten a structure that loops back on itself, so it throws instead of trying.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.