python-read-json-safely.py
import json
from pathlib import Path
def load_json(path: str | Path) -> dict:
path = Path(path)
try:
return json.loads(path.read_text(encoding="utf-8"))
except FileNotFoundError:
raise SystemExit(f"Config not found: {path}")
except json.JSONDecodeError as exc:
raise SystemExit(f"{path} is not valid JSON (line {exc.lineno}, column {exc.colno}): {exc.msg}")
print(load_json("settings.json") if Path("settings.json").exists() else "create settings.json first")