Automate everyday tasks with Python · Lesson 7 of 14
JSON files and settings
Turn Python data into JSON and back with json.dumps, loads, dump and load, pretty-print it, and keep a script's settings in a JSON file.
JSON is a text format for structured data: objects with names and values, lists, numbers, text, true, false and null. Web services send it, many programs save their settings in it, and it maps almost one to one onto Python dictionaries and lists.
- JSON object
{...}↔ Pythondict - JSON array
[...]↔ Pythonlist "text"↔str, numbers ↔int/floattrue/false/null↔True/False/None
Strings: dumps() and loads()
json.dumps() turns Python data into a JSON string, json.loads() turns a JSON string back into Python data. The s stands for string.
import json
order = {"id": 1042, "paid": True, "items": ["tea", "cake"], "note": None}
text = json.dumps(order)
print(text)
back = json.loads(text)
print(back["items"][1], back["paid"], back["note"]){"id": 1042, "paid": true, "items": ["tea", "cake"], "note": null}
cake True NonePretty printing
indent=2 spreads the JSON over several lines so people can read it. ensure_ascii=False keeps letters like é or ü as they are instead of writing codes like \u00e9.
import json
city = {"name": "Malmö", "country": "Sweden", "districts": ["Centrum", "Väster"]}
print(json.dumps(city))
print(json.dumps(city, indent=2, ensure_ascii=False)){"name": "Malm\u00f6", "country": "Sweden", "districts": ["Centrum", "V\u00e4ster"]}
{
"name": "Malmö",
"country": "Sweden",
"districts": [
"Centrum",
"Väster"
]
}Files: dump() and load()
Without the s, json.dump() writes straight into an open file and json.load() reads from one. Here a script reads its settings, changes one value and saves the file again.
import json
with open("settings.json", encoding="utf-8") as f:
settings = json.load(f)
print(settings)
settings["keep_days"] = 14
with open("settings.json", "w", encoding="utf-8") as f:
json.dump(settings, f, indent=2)
with open("settings.json", encoding="utf-8") as f:
print(f.read()){'folder': 'downloads', 'dry_run': True, 'keep_days': 30}
{
"folder": "downloads",
"dry_run": true,
"keep_days": 14
}Settings with defaults
A robust script does not crash when the settings file is missing or broken. It starts from built-in defaults, then lets the file override them. A broken file raises json.JSONDecodeError, which you can catch.
import json
from pathlib import Path
DEFAULTS = {"folder": "downloads", "dry_run": True, "keep_days": 30}
def load_settings(path):
settings = dict(DEFAULTS)
p = Path(path)
if not p.exists():
print(f"{path}: not found, using defaults")
return settings
try:
settings.update(json.loads(p.read_text(encoding="utf-8")))
except json.JSONDecodeError:
print(f"{path}: not valid JSON, using defaults")
return settings
print(load_settings("missing.json"))
print(load_settings("broken.json"))
print(load_settings("mine.json"))missing.json: not found, using defaults
{'folder': 'downloads', 'dry_run': True, 'keep_days': 30}
broken.json: not valid JSON, using defaults
{'folder': 'downloads', 'dry_run': True, 'keep_days': 30}
{'folder': 'downloads', 'dry_run': False, 'keep_days': 30}✎ Exercise
counter.json stores how many times a script has run. Load it, add 1 to runs, set last_file to "report.pdf", save it back with indent=2 and print the new file.
Hint: json.load(f) gives a dictionary. Change it like any dict, then json.dump(data, f, indent=2) into a file opened with "w".
import json
# your code here
Expected output:
{
"runs": 5,
"last_file": "report.pdf"
}Show a solution
import json
with open("counter.json", encoding="utf-8") as f:
data = json.load(f)
data["runs"] += 1
data["last_file"] = "report.pdf"
with open("counter.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
with open("counter.json", encoding="utf-8") as f:
print(f.read()){
"runs": 5,
"last_file": "report.pdf"
}Check yourself
1. What does json.loads take?
loads = load from a string. load reads from a file.
2. What does JSON null become in Python?
null maps to None; true/false map to True/False.
3. What does indent=2 change?
The data is the same; it is just easier for people to read.