On this page
  1. json
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Reading & Writing UTF-8 JSON Files with Error Handling
  7. 2. Serializing Non-JSON Types with default
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects

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

Common Functions

Classes & Objects

Linked from

Related notes