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.
- Write readable JSON with
indentand keep accented text withensure_ascii=False - Save a value to a file with
json.dumpand explain what changes on a round trip (tuples, number keys) - Convert values JSON can't hold, such as sets, before writing
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.
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.
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.
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.
json.dumps(value)returns JSON text;json.dump(value, file)writes it;indent=2andsort_keys=Truemake it readable and stable.ensure_ascii=Falsekeeps 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.