Browse topics

Reading and writing JSON

Version
3.14
Review
Draft

Summary#

dumps and loads convert between Python objects and JSON text. dump and load work with file objects. The default function converts values the encoder does not support.

Syntax#

python
text = json.dumps(value, indent=2, default=convert)
value = json.loads(text)
json.dump(value, file)
value = json.load(file)

Example#

python
import json
from datetime import date


def encode(value):
    if isinstance(value, date):
        return value.isoformat()
    raise TypeError(f"unsupported type: {type(value).__name__}")


record = {"due": date(2026, 3, 1), "tags": ("a", "b"), 7: None}
text = json.dumps(record, default=encode)
print(text)

restored = json.loads(text)
print(restored["tags"], list(restored))

try:
    json.loads("{'single': 'quotes'}")
except json.JSONDecodeError as error:
    print("invalid JSON at", error.lineno, error.colno)

Expected output#

Text
{"due": "2026-03-01", "tags": ["a", "b"], "7": null}
['a', 'b'] ['due', 'tags', '7']
invalid JSON at 1 2

Common mistakes#

TypeError: Object of type set is not JSON serializable names a type that the encoder does not handle. Convert the value first, or pass a default function that returns a supported one.

A round trip does not preserve every type. Tuples return as lists, and supported non-string keys return as strings. The default hook handles unsupported values. Use string keys up front if keys must survive a round trip. To store several values in one JSON document, put them in a list and call dump once. Pass allow_nan=False to reject NaN and infinity when encoding strict JSON.

Version applicability#

The functions shown work on all Python 3 releases. JSONDecodeError was added in Python 3.5. The example needs Python 3.7 or later for the guaranteed dictionary key order in its output and uses an f-string, available from 3.6.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0