Variables in these examples are not permanent storage. Rerunning a program reconstructs its data. JSON is a text format for carrying data between programs or storing it in a file. JSON.stringify(value) produces text. JSON.parse(text) turns valid JSON text back into values.
JSON supports objects, arrays, strings, numbers, booleans, and null. It does not store functions. Its property names and strings use double quotes. A JavaScript object literal is code; JSON is data. Never use eval to read saved data.
Invalid JSON throws an exception. Valid JSON can still describe the wrong thing: "42" parses successfully into a number, not our list of sessions. Parsing and validating the resulting structure are separate jobs. Array.isArray(value) checks whether a value is an array. A real importer also checks every record’s fields and ranges.
This lesson demonstrates the data format, not automatic persistence. Day 7’s downloadable webpage likewise starts fresh on reload. Storage and robust import are good later extensions, after you can validate data safely.
Predict before running
Does parsing recover a number for minutes? Does checking the outer array prove its records are valid?
const sessions = [{ topic: "Loops", minutes: 25, done: false }];
const text = JSON.stringify(sessions);
const restored = JSON.parse(text);
console.log(typeof text);
console.log(Array.isArray(restored));
console.log(restored[0].minutes);Check your prediction
string
true
25Trace each statement in order. If your prediction differed, describe the first place your mental model and the result diverged before trying again.
Valid JSON is not necessarily valid course data
Parsing only checks JSON syntax. A string such as null is valid JSON but is not an array of sessions. After parsing, inspect the shape before using properties. JSON cannot preserve functions or undefined object properties; store data, then let your program supply behavior.
const parsed = JSON.parse("null");
console.log(Array.isArray(parsed));
const record = { topic: "Loops", note: undefined };
console.log(JSON.stringify(record));Check your prediction
false
{"topic":"Loops"}Array.isArray checks the container. A complete import would also validate every record, its field types, ranges, and IDs before replacing current state.
Parsing is not validation
JSON parsing answers whether text follows JSON syntax. It does not answer whether the resulting value is the list of sessions your program expects. Valid JSON can describe null, a number or a record with wrong field types.
Serialization creates text for storage or exchange. Parsing that text creates new ordinary data; it does not reconnect the parsed objects to the original references. Keep these two boundaries distinct: parse the text, then validate the resulting shape before updating application state.
const count = JSON.parse("25");
const missing = JSON.parse("null");
const wrong = JSON.parse('{"minutes":"25"}');
console.log(typeof count);
console.log(missing === null);
console.log(typeof wrong.minutes);Check your prediction
number
true
string All three inputs are valid JSON, so none requires a syntax exception. Each can still be invalid for a session list. Treat a successful parse as the start of validation rather than its conclusion.
const before = [{ topic: "Loops", minutes: 25 }];
const after = JSON.parse(JSON.stringify(before));
after[0].minutes = 30;
console.log(before[0].minutes);
console.log(after[0].minutes);
console.log(before === after);Check your prediction
25
30
false This flat JSON-safe example round-trips without sharing record references. Do not infer that every JavaScript value can round-trip this way; functions and other special values are not ordinary JSON data.
Try the rule on new inputs
Compare malformed text with syntactically valid wrong-shaped text. Decide which needs a parse catch and which needs a decoder failure. Do not replace the current plan until both stages succeed.
Your turn
JSON: practise
Parse the JSON string below. If the result is not an array, throw Error(“Expected a list”). Otherwise print its length, which should be 2. Then try the text 42 and verify rejection.
const text = '["Loops","Arrays"]';
// Parse, check, and print the length.Hint 1: the idea
The JSON can be valid but still have the wrong outer shape.
Hint 2: a first step
Call JSON.parse first, then use !Array.isArray on the result.
Show one solution
const text = '["Loops","Arrays"]';
const topics = JSON.parse(text);
if (!Array.isArray(topics)) {
throw new Error("Expected a list");
}
console.log(topics.length);2The guard confirms only that this is an array. It does not establish that every item is a string. Describe the extra loop you would add to enforce that requirement.
What you should be able to explain
- What does JSON.parse verify?
- Why does valid syntax not guarantee useful data?
- Why should failed import leave existing records intact?
Completion is saved in this browser only. It does not measure mastery.