Python
Public
Safe JSON Load
Load JSON data from a file and handle invalid JSON safely.
#python
#json
#file
#error-handling
Python
import json
from pathlib import Path
file_path = Path("settings.json")
try:
data = json.loads(file_path.read_text(encoding="utf-8"))
print(data)
except FileNotFoundError:
print("settings.json was not found")
except json.JSONDecodeError:
print("settings.json is not valid JSON")
Notes
Use try/except when a file or its content may be missing or invalid.