The problem
You need to read a JSON file and handle potential errors gracefully.
The solution
import json
from pathlib import Path
def read_json(filepath):
"""Read and parse a JSON file safely."""
path = Path(filepath)
if not path.exists():
raise FileNotFoundError(f"File not found: {filepath}")
try:
with open(path, 'r', encoding='utf-8') as f:
return json.load(f)
except json.JSONDecodeError as e:
raise ValueError(f"Invalid JSON in {filepath}: {e}")Parameters
filepathstrPath to the JSON file
Put it to work
# Read configuration
config = read_json('config.json')
print(config['database']['host'])
# With error handling
try:
data = read_json('data.json')
except FileNotFoundError:
print("Config file not found, using defaults")
data = {}Worth knowing
Uses pathlib for cross-platform path handling. UTF-8 encoding handles international characters.