Read and write JSON in Python

The json module, with the two options that make the output readable.

SNP 137 #694 Filed python

python
import json
from pathlib import Path

data = json.loads(Path("posts.json").read_text(encoding="utf-8"))

data.append({"title": "New post", "tags": ["webdev"]})

Path("posts.json").write_text(
    json.dumps(data, indent=2, ensure_ascii=False) + "\n",
    encoding="utf-8",
)

indent=2 makes it readable, ensure_ascii=False keeps "Csige" and friends as they are instead of é. Always say encoding="utf-8"; Windows defaults to something else.

Dates aren't JSON. Pass default=str to dumps to turn them (and anything else unknown) into strings, or convert them yourself first.