Boss lesson · Unit 06
An inventory that saves itself
Load JSON, check it, update it, save it, survive bad input
What you practise
- Parse JSON, check it, update stock, serialise it again, and survive input that is missing or malformed
Try a question from this lesson
Pick one
A shop keeps its stock as JSON text between runs of the program. One tea is sold. What text gets saved?
const saved = '{"tea": 4, "milk": 1}';
const stock = JSON.parse(saved);
stock.tea -= 1;
console.log(JSON.stringify(stock));Correct answer
{"tea":3,"milk":1}
Why
Parse the text into an object, change the object, write it out again. stringify writes strict JSON: keys in double quotes, no extra spaces. That string is what the next run of the program will load.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Load, change, save
Every program that remembers something between runs works in this circle. Text comes in, it is parsed into objects, the objects are changed, and they are written out as text again.
The text spends time outside your program, in a file or on a server. Anything can happen to it there. This lesson is about not trusting it.
saved text --- JSON.parse ---> object
|
change it
|
saved text <-- JSON.stringify -- objectConcept
Check before you trust
Text can be perfect JSON and still be wrong: a quantity of "4" in quotes, or -1, or 2.5.
So after parsing, check the values before you use them. Number.isInteger(x) is true only for whole numbers, and false for strings and everything else.
Throw when a value breaks the rules. A loud error now beats a wrong total next week.
function checkQty(q) {
if (!Number.isInteger(q) || q < 0) {
throw new Error("bad quantity: " + q);
}
return q;
}
console.log(checkQty(4)); // 410 more exercises in the app
- 3× type the answer
- 2× fill the blanks
- 2× multiple choice
- 1× order the lines
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.