← Back to course
Code Crew G6+ / Week 09 / Wednesday
3/6
Week 09 Β· Structured data

Wednesday

Reading JSON with json.load
// Saving lists and dictionaries with JSON
⏱ about 30 min

Wednesday: Reading JSON with json.load

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

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
What type is crew[0] after json.load?
What is crew[1]["role"]?
NUMBERS COME BACK AS NUMBERS
  • Read the question.
  • Tap your answer.
Why can the program add member["missions"] without int()?
If a third record had "missions": 5, what would the Total missions line show?
WHY THIS EXERCISEThe loop adds every record's missions, so 3 plus 4 plus 5 makes 12.
At your computer
1. Make sure crew.json from yesterday is in your mission folder.
2. Type load_crew.py, save it and run it.
3. Open crew.json in IDLE, change a mission number, save it, and run load_crew.py again.
4. Break the file on purpose: delete one comma, save, and run load_crew.py. Read the error last line.
5. Put the comma back and run once more.

Practice: use loaded settings

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
READ USE_SETTINGS.PY
  • Read the question.
  • Tap your answer.
Why can the program multiply settings["volume"] by 10?
You edit the file so "sound": false. What is the last line?
What type is settings after json.load?
Change "volume" to 4 in the file. What is shown? Volume percent: ____
What does settings.get("language", "en") give?
What error appears if the program asks for settings["color"]?
StatementTrue 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.?
WHY THIS EXERCISEload reads the file, so it needs read mode, and it rebuilds Python values like True.

Saving and loading now take one line each. Tomorrow you will read data, change it and write it back.

← Tuesday