json
cheat sheet
Python’s json module at a glance: loads and dumps, files, pretty printing, custom types, hooks, errors, JSON Lines and the python -m json command line.
- Version
- v3.15.2
- Snippets
- 54
- Sections
- 8
Version notes · json 3.15.2
- 3.15 adds
array_hook=toload()/loads(): e.g.array_hook=tuplefor immutable arrays. - 3.15 reads and writes files as UTF-8 by default (PEP 686), the encoding JSON requires.
- 3.14 added
python -m json(alias ofpython -m json.tool) with coloured output. - JSON has no dates, sets, decimals or bytes: convert them with
default=when dumping.
Turn JSON text into Python dicts and lists (loads), and back (dumps). Hooks and a default= function handle the types JSON doesn’t know.
Stdlib
nothing to install
Four functions
load · loads · dump · dumps
Hooks
custom types both ways
CLI
python -m json pretty-prints
Quick start
import jsondata = json.loads('{"name": "Ada", "langs": ["py", "rs"]}')data["langs"].append("go")print(json.dumps(data, indent=2))with open("out.json", "w") as f: json.dump(data, f, indent=2)- Import
- JSON
str/bytes→ Python - Python → JSON
str - Read a file
- Write a file
- Read with pathlib
- Write with pathlib
- Bytes work too (UTF-8/16/32)
The s is for string: loads / dumps work on strings, load / dump on files.
- object {}
- array []
- string
- number
- true / false
- null
- {"1": "a"} # keys become strings
- NaN # not valid JSON (allow_nan=False)
Round trips change types: tuples come back as lists, integer keys come back as strings.
- Pretty-print
- Indent with tabs
- Stable key order (diffs, hashing)
- Most compact
- Keep
é,ø, emoji as-is - Raise on NaN / Infinity
- Drop keys that aren’t str / int / float / bool / None
- Anything unknown →
str()(dates, UUID, Decimal) - Your own fallback
- Use it
- Dataclass → dict first
- Pydantic model (or
model_dump_json()) - Encoder class: override
default(self, o) - Use the class
default is called only for objects json can’t handle. Return something serializable, or raise TypeError.
- Exact decimals (money)
- Every integer as a float
- Objects → attribute access
- Receives
(key, value)pairs (duplicate keys!) - Arrays → tuples (3.15+)
- Fully immutable result (3.15+)
- Handle
NaN/Infinityyourself
- Invalid JSON (a
ValueError) - What and where
- Character offset in the input
JSONDecodeError: Expecting value: empty body?- Single quotes are not JSON: fix the source
Messages
- Pass
default= - Single quotes or a trailing comma
- Several values: JSON Lines? Parse line by line
- Read every line
- Stream a big file
- Append one record
- Build the whole text
- Skip blank lines
One JSON value per line: append-friendly and streamable. Don’t use indent for JSON Lines.
Command line v3.14+
- Validate + pretty-print (coloured)
- Pretty-print from stdin
- Sort keys
- Re-indent into a file
- Minify
- Each line separately
- Keep non-ASCII characters
- Same, on Python ≤ 3.13
