JavaScript AcademyProfessional Engineering
Level 3 · Interactive Web ApplicationsModule 14: State and PersistenceLesson 69 of 150About 40 minutes

Lesson 69: JSON serialization

01Opening question

Storage and networks only carry text. How do you send an array of objects through them and get the same array back?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

JSON.stringify turns data into a string; JSON.parse turns the string back into data. That is how objects travel through storage and networks.

const cart = [{ id: "lamp", qty: 2 }];
const text = JSON.stringify(cart);
console.log(text, typeof text);
const back = JSON.parse(text);
console.log(back[0].qty + 1);

03Objective and prerequisites

Learning objective: Convert data to and from JSON with JSON.stringify and JSON.parse, handle invalid JSON, and know which values JSON cannot represent.

You need: Lesson 68: Local storage and session storage, Lesson 36: Creating JavaScript objects

Skills practised: Browser storage, JSON serialization.

04Explanation

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.

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.

Open the full glossary

06Visual learning object

JSON serialization laboratory. Serialize objects that contain dates, undefined, NaN, Maps and functions, and compare what goes in with what comes back.

Loading the interactive object…

Open the full JSON serialization laboratory page with its guided experiment.

07Examples

ex-069-01Saving an array of objects Browser page (sandboxed preview)

stringify on save, parse on load: the same data comes back.

const cart = [{ id: "lamp", qty: 2 }, { id: "mug", qty: 1 }];
localStorage.setItem("cart", JSON.stringify(cart));
console.log(localStorage.getItem("cart"));
const loaded = JSON.parse(localStorage.getItem("cart"));
console.log(loaded.length, loaded[1].id, loaded === cart);
Sample input
None
Expected output
[{"id":"lamp","qty":2},{"id":"mug","qty":1}] 2 mug false
Common mistake
Saving the object directly with setItem and getting "[object Object]".
Try this
Add a qty to the loaded cart and save it again.
Source
examples/ex-069-01-round-trip.js

ex-069-02What JSON loses Browser page (sandboxed preview)

Some values change or disappear on the way through JSON.

const value = {
  when: new Date("2027-01-02T03:04:05Z"),
  missing: undefined,
  score: NaN,
  tags: new Set(["a"]),
  greet() {}
};
const text = JSON.stringify(value);
console.log(text);
console.log(typeof JSON.parse(text).when);
Sample input
None
Expected output
{"when":"2027-01-02T03:04:05.000Z","score":null,"tags":{}} string
Common mistake
Expecting Dates and Sets to come back as Dates and Sets.
Try this
Store tags as an array with [...value.tags].
Source
examples/ex-069-02-lossy.js

ex-069-03Parsing safely Browser page (sandboxed preview)

Invalid JSON throws; a helper returns a fallback instead.

function loadJSON(key, fallback) {
  const text = localStorage.getItem(key);
  if (text === null) return fallback;
  try {
    return JSON.parse(text);
  } catch (error) {
    console.log("Ignoring bad data:", error.name);
    return fallback;
  }
}
localStorage.setItem("prefs", "{theme: 'dark'}");
console.log(JSON.stringify(loadJSON("prefs", { theme: "light" })));
console.log(JSON.stringify(loadJSON("nothing", [])));
Sample input
None
Expected output
Ignoring bad data: SyntaxError {"theme":"light"} []
Common mistake
Calling JSON.parse directly on stored text and crashing the app when it is corrupted.
Try this
Remove the bad key after ignoring it.
Source
examples/ex-069-03-safe-parse.js

ex-069-04Pretty printing and revivers Browser page (sandboxed preview)

Indentation helps people; a reviver restores Dates.

const text = JSON.stringify({ title: "Launch", at: new Date(Date.UTC(2027, 4, 1)) }, null, 2);
console.log(text);
const event = JSON.parse(text, (key, value) => (key === "at" ? new Date(value) : value));
console.log(event.at instanceof Date, event.at.getUTCMonth());
Sample input
None
Expected output
{ "title": "Launch", "at": "2027-05-01T00:00:00.000Z" } true 4
Common mistake
Parsing dates by hand in many places instead of once in a reviver.
Try this
Write a replacer array that only keeps title.
Source
examples/ex-069-04-reviver.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

"[object Object]" in storage

Serialize before saving.

const profile = { name: "Ada", langs: ["js", "py"] };
localStorage.setItem("profile", profile);
console.log(localStorage.getItem("profile"));

Persist a to-do list

Save and load an array with JSON.

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.

const text = JSON.stringify({ a: 1, b: undefined, c: [undefined, 2] });
console.log(text);

What is printed?

10Debugging investigation

The app crashes after an update

After a new release, some people's app shows nothing. Their browsers still hold data saved by an old version, which stored the count as plain text.

localStorage.setItem("items", "3 items");
function loadItems() {
  return JSON.parse(localStorage.getItem("items")) ?? [];
}
const items = loadItems();
document.getElementById("count").textContent = "Items: " + items.length;
console.log("Items: " + items.length);

More cases in the Debugging Detective Laboratory

11Practical scenario

APIs speak JSON

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?

const prefs = JSON.parse(localStorage.getItem("prefs"));
  • 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

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

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.
  • Parse inside try/catch and validate the shape.

16AI learning prompts

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 explanation JSON 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 prediction JSON 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.
Debugging JSON 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 generation JSON 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 review JSON 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.