Python

Safe JSON Read/Write

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Idiomatic helpers for reading + writing JSON to disk, with atomic writes and pretty-printed output. Catches the common "edit and save → corrupt file on crash" failure mode.
Python
Raw
import json
import os
import tempfile
from pathlib import Path
from typing import Any

def load_json(path: str | Path) -> Any:
    return json.loads(Path(path).read_text(encoding="utf-8"))

def save_json(path: str | Path, data: Any, *, indent: int = 2) -> None:
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix=f".{path.name}-")
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as f:
            json.dump(data, f, indent=indent, ensure_ascii=False, sort_keys=True)
            f.write("\n")
        os.replace(tmp, path)
    except BaseException:
        os.unlink(tmp); raise

state = load_json("config.json")
state["last_run"] = "2025-03-12T14:00:00Z"
save_json("config.json", state)
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.