Skip to main content

Code that compiles on the first try! CodeWithMpia wishes you very happy holidays.✨

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