Lesson 17 of 35Python
Python · Lesson 17 · 30 minutes
JSON – saving data like the pros
What you'll learn
- Understand what JSON is and where it's used
- Save and load dictionaries and lists with json
- Keep working with saved data
What is JSON?
JSON (pronounced “Jason”) is a text format for data. It looks almost exactly like Python dictionaries and lists – and it’s used everywhere: apps store settings with it, websites send data back and forth with it, and Codelix even stores your progress in the browser as JSON.
import json
player = {"name": "Mia", "level": 7, "items": ["sword", "shield"], "active": True}
text = json.dumps(player)
print(text)
print(type(text))json.dumps turns Python data into text. Note the differences: JSON writes true instead of True and always uses double quotes.
And back again
import json
text = '{"name": "Ben", "points": [3, 5, 8]}'
data = json.loads(text)
print(data["name"], sum(data["points"]))json.loads turns the text back into real Python data.
With files: dump and load
Without the s at the end, the functions work directly with files:
import json
settings = {"volume": 80, "language": "en"}
with open("settings.json", "w") as file:
json.dump(settings, file)
with open("settings.json") as file:
loaded = json.load(file)
print(loaded)Remember:
dumps/loads= with strings (text),dump/load= with files.
Quick check
What does this program print?
import json
print(json.dumps({"ok": True, "n": None}))Your task
Your turn
Write two functions. save(data, filename) writes a dictionary as JSON into a file. load(filename) reads the file back in and returns the data. If the file doesn't exist yet, load should return an empty dictionary (tip: catch FileNotFoundError).
import json
def save(data, filename):
pass
def load(filename):
pass
highscores = {"Ana": 120, "Ben": 95}
save(highscores, "highscores.json")
print(load("highscores.json"))- Something to think about
In save use
json.dump(data, file), in load returnjson.load(file)– each inside a withopen(...)block. - Which command helps?
Write the file with
json.dump, not withstr(data)– then it contains real JSON.Put the opening inside try and catch except
FileNotFoundError– thenreturn{}. - Gap code – fill in the ___
import json def save(data, filename): with ___ as file: json.dump(___) def load(filename): try: with ___ as file: return ___ except FileNotFoundError: return ___ highscores = {"Ana": 120, "Ben": 95} save(highscores, "highscores.json") print(load("highscores.json"))
Solve it without hints to earn a ⭐ on your progress page.
Show solution🔒 Unlocks after all hints or 2 checks
Try it yourself first – mistakes teach you the most. Here is one possible solution:
import json
def save(data, filename):
with open(filename, "w") as file:
json.dump(data, file)
def load(filename):
try:
with open(filename) as file:
return json.load(file)
except FileNotFoundError:
return {}
highscores = {"Ana": 120, "Ben": 95}
save(highscores, "highscores.json")
print(load("highscores.json"))