Read a JSON file with clear errors

Load a JSON file and get a readable message when it is missing or malformed.

python beginner #json#files#errors
Apri nel playground
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")