runtime
99 / 250
lesson 99 CSV JSON & JSONL · intermediate

Write Python values as JSON

`json.dumps` turns dictionaries and lists into JSON text and `json.dump` writes it to a file. Some Python values have no JSON form, and a few change on the way through.

You'll be able to
  • Write readable JSON with indent and keep accented text with ensure_ascii=False
  • Save a value to a file with json.dump and explain what changes on a round trip (tuples, number keys)
  • Convert values JSON can't hold, such as sets, before writing
The idea

Going the other way, json.dumps(value) returns JSON text and json.dump(value, file) writes it into an open file. indent=2 spreads it over lines for people to read. By default every non-ASCII character is written as an escape like \u00e9; ensure_ascii=False keeps é as it is (the file must then be written as UTF-8, as always).

Run each example to see what it prints. Running examples doesn't count toward progress.

example-1.py · Compact, then readable
import json

summary = {"store": "Café Lumière", "orders": 3, "late": False, "tags": ["web", "app"], "refund": None}
print(json.dumps(summary))
print(json.dumps(summary, indent=2, ensure_ascii=False))

JSON has objects, arrays, strings, numbers, booleans and null, and nothing else. A set, a date or a Decimal has no JSON form, so dumps refuses it with TypeError rather than guessing. Convert it yourself: a set usually becomes a sorted list.

example-2.py · A set can't be written as JSON
import json

product = {"sku": "HOM-52782", "tags": {"home", "decor"}}
print(json.dumps(product))

A round trip through a file doesn't always give back exactly what you wrote. JSON object keys are always strings, so the number keys of a dictionary come back as text, and tuples come back as lists.

example-3.py · Save a report and read it back
import json

def save_report(path, orders_per_year):
    report = {"orders_per_year": orders_per_year, "busiest": (2024, 58)}
    with open(path, "w", encoding="utf-8") as out:
        json.dump(report, out, indent=2)

save_report("report.json", {2023: 41, 2024: 58})
with open("report.json", encoding="utf-8") as source:
    loaded = json.load(source)
print(loaded)
print(loaded["orders_per_year"]["2024"])

When to use it: saving settings, caching an API response, handing nested data to another program or service. Mistakes to avoid: writing str(value) instead of JSON (that's Python syntax: single quotes, True, None), forgetting encoding="utf-8" when you use ensure_ascii=False, and expecting number keys to survive.

Review
  • json.dumps(value) returns JSON text; json.dump(value, file) writes it; indent=2 and sort_keys=True make it readable and stable.
  • ensure_ascii=False keeps accented text as it is, in a UTF-8 file.
  • Sets, dates and Decimals raise TypeError: convert them first. Tuples come back as lists and number keys as text.
  • Next: JSON Lines, one JSON record per line, for logs and streams.
Practise this

Loading your progress…

To master this lesson, solve both challenges without hints or the answer, and pass the concept check.

Write Python values as JSON — CSV JSON & JSONL · Runtime