Bitpath

Boss lesson · Unit 06

An inventory that saves itself

Load JSON, check it, update it, save it, survive bad input

13 exercisesabout 3 min

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?

JavaScript
const saved = '{"tea": 4, "milk": 1}';
const stock = JSON.parse(saved);
stock.tea -= 1;
console.log(JSON.stringify(stock));

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 -- object

Concept

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.

JavaScript
function checkQty(q) {
  if (!Number.isInteger(q) || q < 0) {
    throw new Error("bad quantity: " + q);
  }
  return q;
}
console.log(checkQty(4)); // 4

10 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.

One email when Bitpath is ready to try. Nothing else. Privacy