JSON.parse()
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — Turning Text Back Into an Object
When your game loads a save file or receives data from a server, what arrives is plain text: a string that looks like an object, but is still just a `string`. If you try to read a property like `.name` directly from that string, you get `undefined`:
const saved = '{"name":"Zap","level":4}';
console.log(typeof saved);
console.log(saved.name);`JSON.parse()` is the exact opposite of `JSON.stringify()`. It reads a JSON string and rebuilds a real JavaScript object (or array) whose properties you can read and use normally:
const saved = '{"name":"Zap","level":4}';
const zap = JSON.parse(saved);
console.log(typeof zap);
console.log(zap.name + " Lv." + zap.level);Tip: when writing a JSON string directly in your code, wrap the outer string in single quotes (`'...'`) so the double quotes (`"..."`) required inside the JSON do not clash with it.
Exercise 2 — A Full Round Trip
`JSON.stringify()` and `JSON.parse()` are designed to work as a pair: 1. `JSON.stringify()` packs a live object into a text string so it can be stored or sent. 2. `JSON.parse()` unpacks that text string into a brand-new object with the same data.
const original = { name: "Zap", moves: ["Spark", "Thunder"] };
const text = JSON.stringify(original);
const copy = JSON.parse(text);
console.log(copy.name);
console.log(copy.moves.length);
console.log(copy === original);Notice that `copy === original` prints `false`. Because `JSON.parse()` builds a completely new object from plain text, `copy` and `original` do not share any references in memory. Combining the two into `JSON.parse(JSON.stringify(original))` is a classic way to make an independent deep copy of an object — including any nested objects or arrays inside it:
const original = { stats: { hp: 40 } };
const copy = JSON.parse(JSON.stringify(original));
copy.stats.hp = 5;
console.log(original.stats.hp);
console.log(copy.stats.hp);Exercise 3 — Strict Text, Loud Failures
Because JSON has strict formatting rules, `JSON.parse()` refuses any string that contains even a tiny mistake — like unquoted keys (`{name: "Zap"}`), single quotes, or a missing closing brace. Whenever `JSON.parse()` receives invalid JSON, it immediately throws a `SyntaxError`:
const good = '{"name":"Zap"}';
const bad = "{name: Zap}";
console.log(JSON.parse(good).name);
console.log(JSON.parse(bad).name); // error!Text coming from a save file or the network is never guaranteed to be valid. Always place `JSON.parse()` inside a `try...catch` block so a corrupted string can be handled cleanly without crashing your program:
const incoming = "{name: Zap}";
try {
const cdm = JSON.parse(incoming);
console.log("Loaded " + cdm.name);
} catch (error) {
console.log("Corrupted save: " + error.name);
}Exercise 4 — Quiz: What Type Comes Back?
What does this code print?
const data = JSON.parse('{"level":4}');
console.log(typeof data);"object""string""json""number"Hint : The method rebuilds a real value from the text.
Exercise 5 — Quiz: Read the Property
What does this code print?
const zap = JSON.parse('{"name":"Zap","level":4}');
console.log(zap.level + 1);541undefinedHint : After parsing, the number is a real number again.
Exercise 6 — Load the Save
Rebuild the Codémon from its saved text and print its name.
Hint : One method reads text into an object, and the object then has its keys back.
Exercise 7 — Quiz: Same Object?
What does this code print?
const a = { x: 1 };
const b = JSON.parse(JSON.stringify(a));
console.log(a === b);falsetrueundefinedHint : Parsing builds something new from text.
Exercise 8 — Parse Safely
Protect the parse so a corrupted save prints a message instead of crashing.
Hint : Outside text can always be invalid, so the read goes in the protected area.
Exercise 9 — parse Cheat Sheet
Match each element with its description.
JSON.parse(text)JSON.stringify(obj)JSON.parse(JSON.stringify(o))Exercise 10 — Save File Reader
Three save files come back from storage. Load every valid one, report the corrupted ones, and never crash.
Step 1: `loadSave(text)` parses the text and returns `"name Lv.X"` from the resulting object. Step 2: loop over `saves`. For each one, try to print the loaded line. On failure print `"Save N corrupted: type"` with the index and the error's `name`. Step 3: print `"Loaded N of M"`.
Expected output:
Zap Lv.4
Save 1 corrupted: SyntaxError
Aquachu Lv.12
Loaded 2 of 3const saves = [
'{"name":"Zap","level":4}',
"{name: Metachu, level: 15}",
'{"name":"Aquachu","level":12}'
];
// Write your function here
// Load the saves here