──────────────────────────────────────

3. Files That Do Work · Read and Round-Trip Settings

Load JSON into a dictionary and serialise an updated setting.

Lesson files · lessons/files-and-formats/json-settings

Before you start
- Read and update a dictionary value by key.
- Recognise numbers and Boolean values in Python.

By the end
- Read a JSON object, increment rounds and print valid JSON with sorted keys.
- Identify how a Boolean looks in Python and in the JSON output.

Where you can use it
Update a quiz’s round count in its settings file, then save the settings as JSON so the quiz can read them again.

JSON is text with a defined grammar. json.loads() turns JSON text into Python values, including dict, list and bool. json.dumps() produces JSON text from supported Python values. Python uses True and False in code, while JSON uses true and false.

Predict
What does json.loads return for a JSON object?
- A Python dictionary.
- A Python string containing the braces.

Worked example (example.py)

import json
settings = json.loads('{"quiet": true, "rounds": 2}')
print(settings["quiet"])
print(json.dumps(settings, sort_keys=True))


Example result
True
{"quiet": true, "rounds": 2}

Read a JSON settings line, add one to rounds, and print the updated JSON with keys sorted.

Starter program (starter.py)

import json
settings = json.loads('{"quiet": true, "rounds": 2}')
print(settings["quiet"])
print(json.dumps(settings, sort_keys=True))


Hint
Assign back to settings["rounds"] and use sort_keys=True so repeated tests produce the same text.

Case 1. Try the sample
Input
{"rounds": 2, "quiet": true}
Expected output
{"quiet": true, "rounds": 3}

Case 2. Zero rounds
Input
{"rounds": 0}
Expected output
{"rounds": 1}

Stretch
Keep a list of player names in the JSON and round-trip it.

Reflect
Where does the Boolean use a lowercase spelling?

Check your prediction
A Python dictionary. loads parses the JSON into structured values.
