crew.json is saved. The next morning a brand new program needs the crew list. Rocket starts writing code to read each line and peel off the brackets.
Halfway through, he stops. "This feels like the hard way," he says. "If dump writes it in one line..."
Raven finishes the thought with him. "What do you notice?" she asks. "Every tool we learned this week came in a pair. dumps and loads. dump and..."
Nova beams. "Would you like a hint?" she asks. "load reads a JSON file and hands back real Python lists and dictionaries, keys and all."
Rocket deletes his bracket-peeling code and writes one line instead.
json.load(f) reads the JSON in an open file and gives back Python data. A JSON array becomes a list, and each JSON object becomes a dictionary. Numbers come back as numbers, not strings.
# load_crew.py
import json
with open("crew.json") as f:
crew = json.load(f)
print(type(crew))
total = 0
for member in crew:
print(f"{member['name']} ({member['role']}): {member['missions']} missions")
total = total + member["missions"]
print("Total missions:", total) <class 'list'> Rocket (engineer): 3 missions Raven (explorer): 4 missions Total missions: 7
After json.load, the settings are an ordinary dictionary. The program can do math with the numbers and use the true or false value in an if.
# use_settings.py
import json
with open("settings.json") as f:
settings = json.load(f)
print("Theme:", settings["theme"])
print("Volume percent:", settings["volume"] * 10)
if settings["sound"]:
print("Sound is on")
else:
print("Sound is off") Theme: night Volume percent: 70 Sound is on
| Statement | True or false? |
|---|---|
| json.load gives back the same shape that was saved. | ? |
| A missing comma in the file can stop json.load with an error. | ? |
| json.load needs the file opened with "w". | ? |
| After loading, true becomes the Python value True. | ? |
Saving and loading now take one line each. Tomorrow you will read data, change it and write it back.