How do I read and parse a JSON file safely in Python?
Answer
Open the file with an explicit encoding inside a `with` block and catch the two errors that matter: a missing file and invalid JSON.
- `FileNotFoundError` means the path is wrong.
- `json.JSONDecodeError` carries the line and column of the problem.
- Use `pathlib.Path` to build paths that work on Windows, macOS and Linux.
Python solution
import json
from pathlib import Path
def load_json(path):
file = Path(path)
try:
with file.open(encoding='utf-8') as f:
return json.load(f)
except FileNotFoundError:
print(f'File not found: {file}')
except json.JSONDecodeError as err:
print(f'Invalid JSON at line {err.lineno}, column {err.colno}: {err.msg}')
return None
data = load_json('config.json')
if data is not None:
print(data.get('name', 'unnamed'))Edited by Jack · joysait@rediffmail.com