Learn Python · lesson 59 of 60 · about 9 minutes
Saving Data with json
Turn dictionaries and lists into JSON text, save them, and load them back.
What you'll learn
- Turn data into JSON text with json.dumps
- Read JSON text with json.loads
- Save and load files with json.dump and json.load
Last week's scores
Games night is every week, and Sam wants to know who did better than last time. Last week's scores are pasted in as JSON text, like {"Ada": 300, "Bo": 550}, and this week's are saved to scores.json, so they can be pasted in next week. The assistant reads the saved file back and prints Saved 4 scores; better than last week: Ada, Dee.
A format everyone understands
JSON is a way of writing data as text. It looks almost like Python dictionaries and lists, and nearly every language and website can read it.
json.dumps(data) turns data into a JSON string. json.loads(text) turns JSON text back into Python data. (The s stands for string.)
To text and back
import json
pet = {"name": "Rex", "age": 3, "tricks": ["sit", "roll"], "vaccinated": True}
text = json.dumps(pet)
print(text)
back = json.loads(text)
print(back["tricks"][1])Output
{"name": "Rex", "age": 3, "tricks": ["sit", "roll"], "vaccinated": true}
rollSaving to a file
json.dump(data, f) writes straight into an open file, and json.load(f) reads it back. Together they let a program remember things between runs, like a high-score table or a to-do list.
Save, then load
import json
scores = {"Ada": 340, "Bo": 510}
with open("scores.json", "w") as f:
json.dump(scores, f)
with open("scores.json") as f:
loaded = json.load(f)
print(loaded["Bo"])Output
510Text in, file out
json.loads(last_text) turns the pasted text into a dictionary, and if the text isn't JSON at all it raises json.JSONDecodeError, so the assistant says so and compares with an empty dictionary instead. dict(scores) turns the list of (name, points) pairs from games night into a dictionary, json.dump writes it to the file, and json.load reads it back into this_week. A player did better if they're in both and this week's points are higher, and sorted lists them by name.
Tip
JSON writes true, false and null where Python has True, False and None, and it always uses double quotes. json.loads converts them back for you.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.