On this page
json
Prev: itertools | Up: stdlib_module | Next: keyword
Rel: email, mailbox, mimetypes, base64, binascii
Ref: docs.python.org — json
Tags: #public #python3 #stdlib
Import
import json
Overview
Standard-library encoder and decoder for JSON (RFC 8259) data interchange. Use json.dumps() / json.loads() for strings and json.dump() / json.load() for file objects; reach for tomllib for TOML config files or csv for flat tabular exports.
Quick Start
import json
payload = {"user": "Ada", "roles": ["admin", "editor"], "active": True}
raw = json.dumps(payload, indent=2, sort_keys=True)
restored = json.loads(raw)
assert restored == payload
Implementation Walkthrough
1. Reading & Writing UTF-8 JSON Files with Error Handling
import json
from pathlib import Path
def save_json(path: Path, data: object) -> None:
path.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
def load_json(path: Path) -> object:
try:
return json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
raise ValueError(f"Invalid JSON in {path} at line {exc.lineno}, col {exc.colno}") from exc
2. Serializing Non-JSON Types with default
Standard JSON only supports dict, list, str, int, float, bool, and None. Supply a default hook for Path, datetime, set, or dataclasses:
import json
from datetime import date
from pathlib import Path
def json_default(obj: object) -> object:
if isinstance(obj, date):
return obj.isoformat()
if isinstance(obj, Path):
return str(obj)
raise TypeError(f"Not JSON serializable: {type(obj).__name__}")
text = json.dumps({"day": date(2026, 12, 1), "file": Path("a.txt")}, default=json_default)
Gotchas & Boundaries
- Object keys are always strings: Integer keys like
{1: "a"}serialize to{"1": "a"}and come back asstronloads(). allow_nan=Trueby default: Python emits non-standardNaN/Infinityunless you passallow_nan=Falsefor strict RFC 8259 output.- No trailing commas or comments: Standard
jsonrejects JSONC/JSON5 syntax; raise/handlejson.JSONDecodeErrorexplicitly. - Prefer
ensure_ascii=Falsefor human-readable files: The default escapes non-ASCII characters as\uXXXX.
Common Functions
- json.dump() —
dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)— Serializeobjas a JSON formatted stream tofp(a.write()-supporting file-like object). - json.dumps() —
dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)— Serializeobjto a JSON formattedstr. - json.load() —
load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)— Deserializefp(a.read()-supporting file-like object containing a JSON document) to a Python object. - json.loads() —
loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)— Deserializes(astr,bytesorbytearrayinstance containing a JSON document) to a Python object.
Classes & Objects
- json.JSONDecodeError — Subclass of ValueError with the following additional properties: msg: The unformatted error message doc: The JSON document being parsed (Methods:
.add_note(),.with_traceback()) - json.JSONDecoder — Simple JSON https://json.org decoder Performs the following translations in decoding by default: +---------------+-------------------+ (Methods:
.decode(),.raw_decode()) - json.JSONEncoder — Extensible JSON https://json.org encoder for Python data structures. (Methods:
.default(),.encode(),.iterencode())
Linked from
- tuts/python3
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/base64
- tuts/python3/stdlib_module/binascii
- tuts/python3/stdlib_module/dbm
- tuts/python3/stdlib_module/email
- tuts/python3/stdlib_module/ftplib
- tuts/python3/stdlib_module/html
- tuts/python3/stdlib_module/http
- tuts/python3/stdlib_module/imaplib
- tuts/python3/stdlib_module/ipaddress
- tuts/python3/stdlib_module/itertools
- tuts/python3/stdlib_module/json/dump
- tuts/python3/stdlib_module/json/dumps
- tuts/python3/stdlib_module/json/JSONDecodeError
- tuts/python3/stdlib_module/json/JSONDecoder
- tuts/python3/stdlib_module/json/JSONEncoder
- tuts/python3/stdlib_module/json/load
- tuts/python3/stdlib_module/json/loads
- tuts/python3/stdlib_module/keyword
- tuts/python3/stdlib_module/mailbox
- tuts/python3/stdlib_module/marshal
- tuts/python3/stdlib_module/mimetypes
- tuts/python3/stdlib_module/nturl2path
- tuts/python3/stdlib_module/pickle
- tuts/python3/stdlib_module/pickletools
- tuts/python3/stdlib_module/poplib
- tuts/python3/stdlib_module/quopri
- tuts/python3/stdlib_module/re
- tuts/python3/stdlib_module/smtplib
- tuts/python3/stdlib_module/socketserver
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/urllib
- tuts/python3/stdlib_module/uuid
- tuts/python3/stdlib_module/webbrowser
- tuts/python3/stdlib_module/wsgiref
- tuts/python3/stdlib_module/xml
- tuts/python3/stdlib_module/xmlrpc
- tuts/python3/tutorials/popular_application_domains/web_development_and_apis
Related notes
- tuts/python3/stdlib_module/base64 Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/binascii Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/email Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/itertools Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/json/dump Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/json/dumps Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/json/JSONDecodeError Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/json/JSONDecoder Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/json/JSONEncoder Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/json/load Linked here; links to this page; shared tags: #stdlib