import json from pathlib import Path from tempfile import NamedTemporaryFile from typing import Any class JsonRepository: def __init__(self, path: Path) -> None: self.path = path def read(self, default: dict[str, Any] | None = None) -> dict[str, Any]: if not self.path.exists(): return default or {} with self.path.open("r", encoding="utf-8") as handle: return json.load(handle) def write(self, payload: dict[str, Any]) -> None: self.path.parent.mkdir(parents=True, exist_ok=True) with NamedTemporaryFile("w", delete=False, dir=self.path.parent, encoding="utf-8") as temp: json.dump(payload, temp, ensure_ascii=False, indent=2) temp_path = Path(temp.name) temp_path.replace(self.path)