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, and how to catch exceptions. It covers the four core functions of the json module and the mistakes people make with them most often.
Four functions, two pairs
The json module converts between JSON text and Python objects. Its four main functions follow a naming rule: a trailing s means "string".
| Function | Works with | Direction |
|---|---|---|
| `json.loads(s)` | a string | JSON text to Python object |
| `json.load(f)` | a file object | JSON text to Python object |
| `json.dumps(obj)` | a string | Python object to JSON text |
| `json.dump(obj, f)` | a file object | Python object to JSON text |
Use the s versions when the data is already in memory, for example from a web response. Use the file versions when you are reading from or writing to a file.
Strings: loads and dumps
json.loads parses JSON text into Python objects. JSON true becomes True, and null becomes None. json.dumps goes the other way and returns a string.
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))The result of loads is an ordinary dict, so you use it like any other dict. The indent and sort_keys arguments only change how the output text looks. The next chapter covers them in detail.
Files: load and dump
json.dump writes to an open file object, and json.load reads from one. Open the file in text mode with an explicit UTF-8 encoding, so that non-ASCII text survives the round trip.
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"])Here ensure_ascii=False writes ü as itself. Without it, json writes the escape sequence \u00fc. Both forms are valid JSON, but the first is easier to read in the file.
What comes back is not always what went in
A round trip through JSON can change your data. Three differences cause most surprises:
- Dict keys always become strings. The key
1is written as"1"and comes back as a string. - Tuples are written as JSON arrays and come back as lists.
- Python
floatvalues such asNaNandInfinityare written as non-standard tokens that strict parsers reject.
import json
original = {1: "one", "pair": (1, 2)}
restored = json.loads(json.dumps(original))
print(restored) # {'1': 'one', 'pair': [1, 2]}Common errors
Most problems with this module come from a small set of mistakes.
- Mixing up
loadandloads. Passing a string tojson.loadfails withAttributeError: 'str' object has no attribute 'read'. Passing a file tojson.loadsraises aTypeError. Check whether you hold a string or a file. - Forgetting to read the response body. Libraries often give you bytes or a response object.
json.loadsacceptsstr,bytes, andbytearray, but not a response object. Decode or extract the body first. - Opening the file in the wrong mode.
json.dumpneeds a file opened for writing in text mode ("w"). A binary file such as"wb"raises aTypeError. - Passing something JSON cannot encode. Types such as
datetimeandsetraiseTypeErrorindumps. A later chapter shows how to handle them with thedefaultargument. - Appending to a JSON file. A file with two
json.dumpcalls contains two documents back to back, whichjson.loadrejects. Read the whole structure, change it, and write it again. For many records, use JSON Lines, which a later chapter covers.
Exercise
You run json.dump({"a": 1}, f) twice on the same open file, then call json.load on that file. What happens, and why?
Show answer
json.load raises json.JSONDecodeError (with the message "Extra data"). The file contains {"a": 1}{"a": 1}, which is two JSON documents, and a JSON parser accepts exactly one document per input. To store several records, write one combined structure such as a list, or use JSON Lines with one object per line.
Exercise
What does json.loads(json.dumps({2: "x", "t": (1, 2)})) return?
Show answer
{'2': 'x', 't': [1, 2]}. JSON object keys must be strings, so the integer key 2 becomes "2". JSON has no tuple type, so the tuple is written as an array and read back as a list.