Sub topic 3
Reading and writing JSON with the json module
This chapter assumes you know basic Python syntax, dicts, lists, and strings, the with statement for files, and how to handle exceptions. You should also know that JSON values map to Python types (objects to dicts, arrays to lists, true/false to True/False, null to None). Here you will learn the four functions that move data between JSON text and Python objects, and the mistakes people make with them.
The four functions and what they do
The json module is in the standard library. Its core API is four functions, and the names follow one pattern:
| Function | Input | Output | Works with |
|---|---|---|---|
| `json.loads(s)` | JSON text (`str`, `bytes`, or `bytearray`) | Python object | strings in memory |
| `json.dumps(obj)` | Python object | JSON text (`str`) | strings in memory |
| `json.load(fp)` | open file object | Python object | files |
| `json.dump(obj, fp)` | Python object and open file object | `None`, text is written to the file | files |
The trailing s stands for "string". loads means "load from string" and dumps means "dump to string". The versions without the s read from or write to a file object. They are thin wrappers: json.load(fp) reads the whole file and calls loads on the result, and json.dump(obj, fp) builds the text in chunks and writes each chunk to fp.
Parsing and producing strings
Start with the string functions, because they show the type mapping most plainly.
import json
text = '{"name": "Ada", "langs": ["Python", "C"], "active": true, "score": null}'
data = json.loads(text)
print(data["active"], data["score"]) # True None
print(json.dumps(data, indent=2, sort_keys=True))loads returns a dict here because the top-level JSON value is an object. Keep in mind that the top-level value can be any JSON value, not only an object or array. json.loads("42") returns the integer 42, and json.loads('"hi"') returns the string 'hi'. Code that assumes data is always a dict will fail when the input is something else, so check the type when the input comes from outside your program.
dumps returns a str. The call above passes two optional arguments, indent=2 and sort_keys=True. Both change only the formatting of the output. A later chapter in this tutorial covers formatting in detail, so this chapter uses them only to make the output readable.
Round trips are not always exact
Converting to JSON and back gives you an equal object in the simple cases, but several things change on the way:
- Tuples become arrays, so they come back as lists.
- Dict keys must be strings in JSON. Integer, float, boolean, and
Nonekeys are converted to strings, so{1: "a"}comes back as{"1": "a"}. True,False, andNonebecometrue,false, andnull, and map back correctly.- Large integers survive, because Python integers have no size limit, but other languages reading the same JSON may lose precision.
import json
original = {"point": (1, 2), 1: "one"}
restored = json.loads(json.dumps(original))
print(restored) # {'point': [1, 2], '1': 'one'}
print(restored == original) # FalseIf your program depends on tuples or non-string keys, convert them explicitly after loading.
Reading and writing files
For files, use json.load and json.dump. Open the file with an explicit encoding, as the file-handling chapter explained.
import json
from pathlib import Path
path = Path("config.json")
with path.open("w", encoding="utf-8") as f:
json.dump({"city": "Zürich", "retries": 3}, f, indent=2, ensure_ascii=False)
with path.open(encoding="utf-8") as f:
config = json.load(f)
print(config["city"])Three details matter here.
- Text mode.
json.dumpwritesstrvalues, so the file must be opened in text mode ("w", not"wb").json.loadaccepts a file opened in text mode or in binary mode. In binary mode it detects UTF-8, UTF-16, or UTF-32 from the bytes. Text mode withencoding="utf-8"is the clearer choice. - UTF-8 is the standard. The JSON specification (RFC 8259) requires UTF-8 for JSON exchanged between systems. Writing with
encoding="utf-8"keeps your files readable by other tools and avoids the platform default, which is not UTF-8 on every system. ensure_ascii=False. By defaultdumpanddumpsescape every non-ASCII character as\uXXXX. Withensure_ascii=Falsethe characters are written as they are, which is why the example above needs the UTF-8 encoding on the file. Both forms are valid JSON, andjson.loadreads them identically.
Writing a file safely
If json.dump raises an exception halfway through, for example because it meets a value it cannot serialize, the file you opened with "w" has already been truncated and may contain partial output. For files that matter, serialize to a string first, then write it. If serialization fails, the old file stays untouched.
import json
from pathlib import Path
def save_json(path, obj):
text = json.dumps(obj, indent=2, ensure_ascii=False) # may raise before any write
Path(path).write_text(text, encoding="utf-8")
save_json("settings.json", {"theme": "dark", "tags": ["a", "b"]})
print(Path("settings.json").read_text(encoding="utf-8"))The cost is that the whole text sits in memory at once. For very large data, see the chapter on streaming and JSON Lines. For stronger guarantees against a crash during the write itself, write to a temporary file and rename it over the target with Path.replace.
Reading JSON from other sources
loads accepts bytes, which is what many network libraries return. It detects the encoding for you, so you do not need to decode first.
import json
raw = b'{"status": "ok", "items": [1, 2, 3]}'
data = json.loads(raw)
print(sum(data["items"])) # 6For a response from a web API, the same function applies. With the requests library, response.json() calls it for you, but the underlying behavior and errors are the same ones described here.
Common errors
Most problems with this module fall into a few groups.
Mixing up the functions
Passing a string to load, or a file to loads, raises an error. The message mentions a missing read method or an unsupported type.
import json
try:
json.load('{"a": 1}') # a str has no read() method
except AttributeError as e:
print(e)
try:
json.loads(open("config.json", encoding="utf-8")) # a file is not a str
except TypeError as e:
print(e)The rule: if the name ends in s, you give it a string. If not, you give it a file.
Reading a file twice
json.load(f) reads the file to the end. A second json.load(f) on the same open file finds no data and raises JSONDecodeError. A file holds one JSON document, so load it once and keep the result. If you need several records in one file, use JSON Lines, which a later chapter covers.
Single quotes and Python syntax
A Python dict printed with print or str is not JSON. It uses single quotes, True, and None. Use json.dumps to produce JSON, and do not build JSON by hand with string formatting.
import json
data = {"ok": True, "value": None}
print(str(data)) # {'ok': True, 'value': None} (not JSON)
print(json.dumps(data)) # {"ok": true, "value": null} (JSON)Unsupported values
dumps raises TypeError for objects it cannot represent, such as datetime, set, Decimal, or instances of your own classes. A later chapter covers the default parameter that fixes this. Float values nan, inf, and -inf are a separate case. Python writes them as NaN, Infinity, and -Infinity, which are not valid JSON, and many other parsers reject them. Pass allow_nan=False if you want dumps to raise ValueError instead of producing invalid output.
import json
print(json.dumps({"x": float("nan")})) # {"x": NaN} (not valid JSON)
try:
json.dumps({"x": float("nan")}, allow_nan=False)
except ValueError as e:
print(e)Duplicate keys
JSON text can contain the same key twice, such as {"a": 1, "a": 2}. Python does not raise an error. The last value wins, so json.loads returns {"a": 2}. If duplicates indicate a bug in your data, use the object_pairs_hook parameter, which receives the key-value pairs before they are merged, and raise an error there.
Useful options on loads and load
Most programs use only the defaults, but three options are worth knowing.
object_pairs_hookreceives each JSON object as a list of(key, value)pairs. Use it to detect duplicate keys, or passcollections.OrderedDictif you need that type.parse_floatandparse_inttake a function to build numbers. Passingparse_float=decimal.Decimalkeeps exact decimal values, which matters for money.object_hookreceives each decoded dict and returns a replacement. It is the usual way to turn dicts back into custom objects.
import json
from decimal import Decimal
text = '{"price": 19.99, "qty": 3}'
data = json.loads(text, parse_float=Decimal)
print(data["price"] * data["qty"]) # 59.97With plain floats, 19.99 * 3 gives 59.97 only by luck of rounding in some cases and 59.969999999999995 in others, so Decimal is the safer choice for currency.
Choosing the right function
Use this guide when you are unsure which function to call.
- You have a string or bytes from a network call, a database column, or a test:
loads. - You have a file and the data fits in memory:
load. - You need text to send over a network, store in a database, or log:
dumps. - You are writing a file and a half-written file would cause harm:
dumpsfirst, then write the string. - You are writing a file and a partial result is acceptable:
dump.
Exercise
A script runs json.dump(report, f) on a file opened with open("report.json", "w"). The report contains a datetime value, and the script crashes with TypeError. What state is report.json in afterwards, and how would you change the code so a failure leaves the previous file intact?
Show answer
Opening with "w" truncates the file immediately, so after the crash it is empty or holds partial JSON, and the previous contents are lost. Call json.dumps(report) first to get a string, so the error is raised before the file is opened for writing, then write that string with Path("report.json").write_text(text, encoding="utf-8"). The datetime itself needs a default function, which a later chapter covers.
Exercise
What does this code print, and why? import json print(json.loads(json.dumps({"a": (1, 2), 3: None})))
Show answer
It prints {'a': [1, 2], '3': None}. The tuple becomes a JSON array and returns as a list, the integer key 3 is converted to the string "3", and None becomes null and returns as None.