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.

About 14 minutes · code runs in your browser, nothing to install

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 {...} ↔ Python dict
  • JSON array [...] ↔ Python list
  • "text" ↔ str, numbers ↔ int / float
  • true / 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.

Pythoneditable
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"])
Output
{"id": 1042, "paid": true, "items": ["tea", "cake"], "note": null}
cake True None

Pretty 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.

Pythoneditable
import json

city = {"name": "Malmö", "country": "Sweden", "districts": ["Centrum", "Väster"]}

print(json.dumps(city))
print(json.dumps(city, indent=2, ensure_ascii=False))
Output
{"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.

Pythoneditable
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())
Output
{'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.

Pythoneditable
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"))
Output
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}
Tip: JSON has no comments and no trailing commas. If people edit your settings file by hand, a friendly error message like the one above saves them a lot of confusion.

✎ 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".

Your codewrite your answer, then Run
import json
# your code here

Expected output:

{
  "runs": 5,
  "last_file": "report.pdf"
}
Show a solution
Solutioneditable
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())
Output
{
  "runs": 5,
  "last_file": "report.pdf"
}

Check yourself

1. What does json.loads take?

2. What does JSON null become in Python?

3. What does indent=2 change?

Spotted a mistake on this page? Tell us