PythoneasyPython

Read and Parse JSON File

Safely read and parse a JSON file with error handling.

01

The problem

You need to read a JSON file and handle potential errors gracefully.

02

The solution

Python
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}")

03

Parameters

filepathstr

Path to the JSON file

04

Put it to work

Example
# 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.