Skip to main content

Load JSON File

Description

The load_json function reads and parses a JSON file, returning its contents as a dictionary. If the file does not exist or contains invalid JSON, it returns an empty dictionary instead of raising an error.

Function Signature:

def load_json(file_path: str) -> dict:

Parameters

  • file_path (str): The path to the JSON file to read.

Returns

  • dict: The contents of the JSON file as a dictionary, or an empty dictionary if the file is missing or cannot be parsed.

Example Usage

config_data = load_json("/path/to/settings.json")
if not config_data:
print("No valid config found, using defaults.")

Behavior

  • If the file does not exist, the function silently returns an empty dictionary.
  • If the file exists but cannot be parsed due to invalid JSON, it returns an empty dictionary.
  • Uses UTF-8 encoding to open and read the file.

Error Handling

  • FileNotFoundError: Handled silently by returning an empty dictionary.
  • json.JSONDecodeError: Handled by returning an empty dictionary.