
Side Quest: Broken or Just Wrong?
Loading saved data can fail in two very different ways:
| Problem | Example text | What happens |
|---|---|---|
| Broken JSON | {"level": 3, |
json.loads raises json.JSONDecodeError |
| Wrong shape | [3, "Amber"] |
loads fine, but it's a list, not the dict you need |
Broken JSON isn't JSON at all: a missing bracket, single quotes
instead of double quotes, or an empty file. Wrong shape is
valid JSON, just not the structure your program expects. Even
"hello", 42 and null are valid JSON on their own!
Checking the shape
isinstance(value, kind) asks "is this value that kind of thing?"
isinstance({"level": 3}, dict) # True
isinstance([3], dict) # False
isinstance(3, int) # True
Check from the outside in: is it a dict? Does it have the key? Is
the value the right type? data.get("level") gives None for a
missing key, and None is not an int, so one check covers both.
Keeping the two problems apart gives much better messages. "Your save file is damaged" is different from "this file belongs to another program".
Assignment
Complete check_save(text). It returns one of three strings:
"broken"iftextisn't valid JSON. Catch onlyjson.JSONDecodeError."wrong shape"if it's valid JSON but not a dict whose"level"is anintand whose"lanterns"is alist."ok"otherwise. Extra keys are fine.
Complete check_save(text). It returns one of three strings:
"broken"iftextisn't valid JSON. Catch onlyjson.JSONDecodeError."wrong shape"if it's valid JSON but not a dict whose"level"is anintand whose"lanterns"is alist."ok"otherwise. Extra keys are fine.
Press Run to try your code, then Check to test it.