
Code
Save the Quest
JSON is the most popular format for saving and sending structured data: nested dicts and lists, as text.
import json
progress = {"level": 3, "lanterns": ["Amber Isle"], "done": False}
text = json.dumps(progress, indent=2) # Python -> JSON string
back = json.loads(text) # JSON string -> Python
For files, use json.dump(obj, f) and json.load(f) (no s:
the s in dumps/loads stands for string).
| Python | JSON |
|---|---|
dict |
object {...} (keys become strings!) |
list, tuple |
array [...] |
str, int, float |
string, number |
True / False / None |
true / false / null |
If the text isn't valid JSON, json.loads raises
json.JSONDecodeError (a kind of ValueError).
Assignment
- Complete
save_progress(path, progress): write the dict topathas JSON withindent=2. - Complete
load_progress(path): read and return the dict. If the file is missing or contains broken JSON, return a fresh default:{"level": 1, "lanterns": []}.
- Complete
save_progress(path, progress): write the dict topathas JSON withindent=2. - Complete
load_progress(path): read and return the dict. If the file is missing or contains broken JSON, return a fresh default:{"level": 1, "lanterns": []}.
main.py Python sleeping
Press Run to try your code, then Check to test it.