Skip to main content

Save JSON to File

Description

The save_json function saves a Python dictionary to a JSON file. It ensures that the directories for the specified file path exist before attempting to write. The function writes the data in a formatted manner for readability.

Function Signature:

def save_json(file_path: str, data: dict) -> None:

Parameters

  • file_path (str): The path to the JSON file where the data will be saved.
  • data (dict): The dictionary that will be saved to the file.

Returns

  • None: The function does not return anything. It writes the data to the specified file.

Example Usage

config_data = {"setting1": "value1", "setting2": "value2"}
save_json("/path/to/settings.json", config_data)

Behavior

  • The function ensures that the directory of the specified file path exists. If it does not, it creates the necessary directories.
  • The data is written to the file with an indentation of 4 spaces for better readability.

Error Handling

  • OSError: If there is an error in writing the file or creating the directory, it will raise an exception.
  • TypeError: If the data provided is not a dictionary, the function may raise an error.