Aller au contenu principal

Le site sera en maintenance le 19/04/2026 entre 09h30 et 12h00.

Aller au contenu principal

Lire un fichier JSON avec gestion d'erreurs

Fonction robuste pour lire un fichier JSON avec gestion des exceptions FileNotFoundError et JSONDecodeError.

Langage

python

Accès

Libre

import json
from pathlib import Path


def load_json(filepath):
    """Load JSON file with proper error handling"""
    try:
        return json.loads(Path(filepath).read_text(encoding="utf-8"))
    except FileNotFoundError:
        print(f"File {filepath} not found")
        return None
    except json.JSONDecodeError as e:
        print(f"JSON error: {e}")
        return None