json

Four functions do almost all the work: loads/dumps for strings, load/dump for files. The traps are in the type mapping — tuples come back as lists, keys come back as strings.

Data formatsPython 2.6+Live demo
Import
import json
from json import dumps, loads
Public API
dump, dumps, load, loads, JSONEncoder, JSONDecoder, JSONDecodeError
Spec
RFC 8259 / ECMA-404 — plus NaN and Infinity, which Python accepts by default
Speed
C accelerator _json used automatically (Modules/_json.c)
CLI
python -m json.tool data.json

Demo

Live evaluation
Parse JSON text into Python, then serialize it back. Compare what comes out with what went in.
Try:
Inputs
textstra JSON document
Code
import json
data = json.loads('{"name": "Zoë", "id": 7}')
json.dumps(data, sort_keys=True)
Result
'{"id": 7, "name": "Zo\\u00eb"}'

Three things the round trip exposes: non-ASCII text is escaped by default ("Zo\u00eb" — pass ensure_ascii=False to keep it), 1.0 stays a float while 1 stays an int, and a duplicate key silently keeps the last value. Python-style single quotes are not JSON at all.

Members

Common patterns

Read a JSON file
json.load takes an open file; say the encoding explicitly.
import json
with open('config.json', encoding='utf-8') as f:
    config = json.load(f)
Write a JSON file
indent for humans, ensure_ascii=False to keep non-ASCII text readable.
import json
with open('out.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, indent=2, ensure_ascii=False)
Serialize types json does not know
default= is called for every unsupported object; return something serializable.
import json
json.dumps(record, default=str)  # datetime, Decimal, UUID → their str()
Validate on the command line
json.tool pretty-prints a file and exits non-zero on invalid JSON.
# shell:
# python -m json.tool data.json

Examples

1. JSON object → dict
import json json.loads('{"a": 1, "b": [true, null]}')
Returns
{'a': 1, 'b': [True, None]}
2. dict → JSON text
import json json.dumps({'a': 1, 'b': [True, None]})
Returns
'{"a": 1, "b": [true, null]}'
3. Tuples come back as lists
import json json.loads(json.dumps((1, 2)))
Returns
[1, 2]
4. Keys come back as strings
import json json.loads(json.dumps({1: 'a'}))
Returns
{'1': 'a'}
5. Compact output
import json json.dumps({'a': [1, 2]}, separators=(',', ':'))
Returns
'{"a":[1,2]}'
6. Sets are not serializable
import json json.dumps({1, 2})
Returns
TypeError: Object of type set is not JSON serializable

Pitfalls

1. Using str() or repr() to produce JSON
A Python dict repr uses single quotes, True and None — it is not JSON, and loads rejects it.
str(dict)
import json
json.loads(str({'ok': True}))
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
json.dumps
import json
json.loads(json.dumps({'ok': True}))
{'ok': True}
2. datetime is not JSON serializable
dumps only knows dict, list, tuple, str, int, float, bool and None. Everything else needs default= (or a custom JSONEncoder).
plain dumps
import json
from datetime import date
json.dumps({"day": date(2026, 9, 29)})
TypeError: Object of type date is not JSON serializable
default=str
import json
from datetime import date
json.dumps({"day": date(2026, 9, 29)}, default=str)
'{"day": "2026-09-29"}'

When to use

Use it
  • Exchanging data with web APIs, JavaScript and other languages
  • Human-readable config and data files
  • Parsing untrusted input — json never executes code
Reach for something else
  • Round-tripping arbitrary Python objects (tuples, sets, dates) → pickle, or a schema library
  • Tabular data → csv
  • Config with comments → tomllib (reading TOML, 3.11+)

Notes

CPython impl
Lib/json/ in pure Python, with Modules/_json.c used automatically for scanning and encoding — its error messages are what you see
Encoding
dumps escapes non-ASCII as \uXXXX unless ensure_ascii=False
Floats
Written with repr(), so they round-trip exactly; NaN and Infinity are emitted unless allow_nan=False

FAQ

loads parses a str (or bytes) you already have; load reads from a file object and parses its content. Likewise dumps returns a str and dump writes to a file. The trailing s stands for "string".