Read and write JSON files in Python: json module, done right
Python's standard library json module handles reading and writing JSON without any third-party install. The confusion usually starts with its four similarly-named functions. This guide sorts them out and shows the file pattern you actually want, per the official documentation.
dumps/loads vs dump/load
Rule of thumb from the docs: functions with an s work on strings, functions without work on file-like objects.
| Function | Direction | Works on |
|---|---|---|
json.dumps(obj) | Python to JSON | returns a string |
json.loads(s) | JSON to Python | takes a string |
json.dump(obj, f) | Python to JSON | writes to a file |
json.load(f) | JSON to Python | reads from a file |
Write a JSON file
import json
data = {"name": "Nethum", "services": ["web", "bots"], "active": True}
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
Two flags worth knowing: ensure_ascii=False keeps non-English text (Arabic names, for example) readable instead of escaped, and indent=2 makes the file human-readable.
Read it back
with open("data.json", "r", encoding="utf-8") as f:
data = json.load(f)
print(data["services"][0]) # web
Type mapping to remember
Objects become dicts, arrays become lists, strings stay strings, numbers become int or float, true/false become True/False, and null becomes None. The one-directional catch: JSON has no tuple or set, so a Python tuple comes back from load as a list.
Common errors
- json.JSONDecodeError: the file is not valid JSON; often a trailing comma or single quotes instead of double.
- UnicodeDecodeError: you opened the file without
encoding="utf-8"on a file that contains non-ASCII text. - TypeError: Object of type ... is not JSON serializable: you tried to dump something like a datetime; convert it to a string first.
Next: calling APIs with requests (Arabic) and virtual environments with venv.
