JSON and Serialization
Build a precise mental model of JavaScript values, scope, functions, objects, arrays and asynchronous behavior, then implement and debug real utilities from first principles instead of memorizing outputs.
What you will be able to do
#- Predict which values JSON.stringify keeps and which it drops.
- Use a replacer and a reviver to control conversion.
- Choose between JSON cloning and structuredClone.
Overview
#JSON is a data format, not JavaScript
JSON supports objects, arrays, strings, numbers, booleans and null. It has no undefined, functions, symbols or comments. JSON.stringify silently drops object properties whose value is undefined or a function, and converts undefined array entries to null.
console.log(JSON.stringify({ a: undefined, b: () => {}, c: 1 })); // {"c":1}
console.log(JSON.stringify([undefined, 1])); // [null,1]
Replacers, revivers and toJSON
The second argument to stringify is a replacer that can filter keys or transform values, and the second argument to parse is a reviver that runs on each key as the value is rebuilt. A value with a toJSON method, such as Date, is serialized through that method, which is why a Date becomes an ISO string.
console.log(JSON.stringify(new Date(0))); // "1970-01-01T00:00:00.000Z"
Limits and alternatives
Cyclic references throw a TypeError, and BigInt throws because it cannot be represented. JSON.parse throws on malformed input, so wrap it when the source is untrusted. structuredClone copies many built-in types, including Map, Set and Date, and handles cycles, but it is a memory copy rather than a serialization format.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
What does this line print?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.javascriptconsole.log(JSON.stringify({ a: undefined, b: () => {}, c: 1 }), JSON.stringify([undefined, 1]));Exercise 2Explain
Explain why JSON.stringify throws on a cyclic object and how you would work around it.
starter.textconst a = {}; a.self = a; console.log(JSON.stringify(a));Reveal the reference answer
reference.textJSON has no way to express a reference, so stringify would recurse forever on a cycle. It detects the cycle and throws a TypeError instead. To serialize such data I either replace the back-reference with an identifier using a replacer and a seen set, or use a format that supports references, and I document the choice.Authored expected output: TypeError: Converting circular structure to JSON
The error is a safety feature. A replacer that tracks visited objects can break the cycle deliberately rather than by accident.
Exercise 3Implement
Implement `safeJsonParse(text, fallback)` so it returns the parsed value or the fallback when the text is invalid. Running `console.log(safeJsonParse('{', 'default'), safeJsonParse('{"ok":true}', null).ok)` should print `default true`.
starter.javascriptfunction safeJsonParse(text, fallback) { // your code here }Reveal the reference answer
reference.javascriptfunction safeJsonParse(text, fallback) { try { return JSON.parse(text); } catch { return fallback; } }Authored expected output: default true
JSON.parse throws a SyntaxError on malformed input. Catching it and returning a caller-supplied fallback keeps a bad payload from crashing the caller.
Exercise 4Debug
This clone is meant to be independent but changing the copy also changes the original. Find and fix the bug.
starter.javascriptconst original = { nested: { count: 1 } }; const copy = { ...original }; copy.nested.count = 2; console.log(original.nested.count, copy.nested.count);Reveal the reference answer
reference.javascriptconst original = { nested: { count: 1 } }; const copy = structuredClone(original); copy.nested.count = 2; console.log(original.nested.count, copy.nested.count);Authored expected output: 1 2
A spread copy is shallow, so copy.nested and original.nested reference the same object. Mutating copy.nested.count changes the original too, and both values print 2. structuredClone produces a genuinely independent deep copy, so the original stays 1 and the copy becomes 2.
Exercise 5Test
Write assertions that prove a reviver can restore a Date and that stringify drops a function.
starter.javascriptfunction assertEqual(actual, expected, label) { if (actual !== expected) throw new Error(label + ': expected ' + expected + ' but got ' + actual); }Reveal the reference answer
reference.javascriptconst text = JSON.stringify({ when: new Date(0) }); const revived = JSON.parse(text, (key, value) => key === 'when' ? new Date(value) : value); assertEqual(revived.when instanceof Date, true, 'reviver restores a Date'); assertEqual(JSON.stringify({ run: () => {} }), '{}', 'functions are dropped'); console.log('all assertions passed');Authored expected output: all assertions passed
A Date serializes to an ISO string, and a reviver can turn that string back into a Date. Functions have no JSON representation, so the property disappears.
Exercise 6Interview
What would you check before sending a large object as a JSON API payload?
Reveal the reference answer
reference.textI would check for values JSON cannot represent, such as functions, undefined, BigInt and cycles, and decide explicitly whether to drop, convert or reject them. I would confirm the payload size and that dates are ISO strings, avoid sending secrets, and validate the shape on the server rather than trusting the client. If the data needs richer types I would choose a format that supports them instead of forcing JSON.The answer should name the JSON value limits, an explicit policy for each, and server-side validation rather than silent assumptions.
Common misconceptions
#- JSON.stringify keeps undefined properties so they can be restored later.
- JSON.parse never throws on data from a network response.
- JSON round-tripping is a correct deep clone for every value.
Follow-up practice
#- javascript-foundations-browser-storage
- javascript-foundations-objects-and-prototypes
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.