Learning objective: Convert data to and from JSON with JSON.stringify and JSON.parse, handle invalid JSON, and know which values JSON cannot represent.
JSON (JavaScript Object Notation) is a text format for data: objects, arrays, strings, numbers, booleans and null.
JSON.stringify(value) converts a value to a JSON string. JSON.parse(text) converts JSON text back into a value.
To save an object in localStorage: setItem(key, JSON.stringify(obj)). To load it: JSON.parse(getItem(key)).
JSON keys must use double quotes, and it has no comments, no trailing commas, no functions and no undefined.
JSON.parse throws a SyntaxError on invalid text, for example data saved by an old version or edited by hand. Always wrap it in try/catch and fall back to a default.
Some values do not survive: undefined and functions are dropped from objects (and become null in arrays), NaN and Infinity become null, Dates become ISO strings, and Map and Set become {}.
JSON.stringify(value, null, 2) pretty-prints with two-space indentation. A replacer array or function controls which keys are written.
A reviver function in JSON.parse(text, reviver) can turn ISO date strings back into Date objects. Validate parsed data before trusting its shape.
05Definitions
JSON
A text format for structured data based on JavaScript object and array syntax.
Serialization
Converting data in memory into a format such as a JSON string for storage or transfer.
JSON.stringify
A method that converts a value into a JSON string.
JSON.parse
A method that converts JSON text back into a JavaScript value; it throws on invalid input.
Reviver
A function passed to JSON.parse that can transform values as they are read.
JSON serialization laboratory. Serialize objects that contain dates, undefined, NaN, Maps and functions, and compare what goes in with what comes back.
function saveTodos(todos) {
// TODO
}
function loadTodos() {
// TODO: return the saved array, or [] if nothing is saved
}
console.log(loadTodos().length);
saveTodos([{ text: "Read", done: false }, { text: "Run", done: true }]);
const todos = loadTodos();
console.log(todos.length, todos[1].done);
Load with validation
Parse safely and check the shape.
// Write loadSettings(): reads "settings" from localStorage and returns it
// only if it parses AND is an object with version === 2 and a string
// theme. Otherwise it returns { version: 2, theme: "light" }.
09Prediction
Commit to an answer first, then run the real code to compare.
Almost every web API sends and receives JSON. A weather app receives a JSON forecast, parses it, shows it and stores the last response in local storage so it can show something while offline.
const response = '{"city":"Toronto","temps":[3,5,4]}';
const data = JSON.parse(response);
console.log(data.city, Math.max(...data.temps));
12Knowledge check
1. What does JSON.stringify return?
An object
A string
A Map
A number
2. What does JSON.parse("[1, 2]").length give?
"2"
2
5
It throws
3. Why does the app crash on start for some users?
Stored text may not be valid JSON and parse throws
getItem is slow
JSON.parse needs two arguments
Arrays cannot be stored
4. What happens to a Date in JSON.stringify?
It is dropped
It becomes an ISO date string
It stays a Date
It becomes a number
5. Which is valid JSON?
{name: "Ada"}
{"name": "Ada"}
{'name': 'Ada'}
{"name": "Ada",}
6. Which is safer when loading saved data?
JSON.parse(getItem(key))
A helper that handles null, catches SyntaxError and checks the shape
eval(getItem(key))
String(getItem(key))
13Solutions and tests
Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.
Automated acceptance tests for this lesson
These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.
"[object Object]" in storage: Prints JSON; Loads back
Persist a to-do list: Prints 0 then 2 true; Loaded data is a copy
Load with validation: Prints light, light, dark; null JSON falls back; Nothing stored falls back
The lesson lives in the companion repository at curriculum/level-03-interactive-web-applications/module-14-state-and-persistence/lesson-069-json-serialization/. Every example on this page is generated from those files.
These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.
15Summary and next steps
JSON is text that represents objects, arrays and simple values.
stringify to save or send; parse to load or receive.
Some values (undefined, functions, Date, Map, Set, NaN) do not survive unchanged.
Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.
Concept explanationJSON serialization
Context: I am learning JSON serialization in JavaScript.
Task: Explain JSON.stringify and JSON.parse, including values that do not survive, with examples.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code predictionJSON serialization drill
Context: I have practised JSON serialization.
Task: Give me six stringify/parse puzzles and ask what each prints.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
DebuggingJSON serialization bug
Context: My saved cart comes back as "[object Object]".
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generationJSON serialization practice
Context: I finished the JSON serialization exercises.
Task: Create three exercises that save and load objects with JSON and handle bad data.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code reviewJSON serialization review
Context: Here is my code that uses JSON serialization.
Task: Review my JSON code for unsafe parsing and values that are lost.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.