Write Value to JSON File
Description
The write_json_value
function writes a value to a JSON file at a specified path. It loads the JSON data from the file, updates the value at the given path, and saves the updated data back to the file.
Function Signature:
def write_json_value(file_path: str, json_path: str, value: Any) -> None:
Parameters
- file_path (str): The full path to the JSON file to be written to.
- json_path (str): A dot-separated string representing the path to the value within the JSON structure (e.g.,
"user.profile.name"
). - value (Any): The value to be written at the specified path.
Returns
- None: This function does not return a value. It updates the file in-place.
Example Usage
file_path = "/path/to/data.json"
json_path = "user.profile.name"
value = "John"
write_json_value(file_path, json_path, value)
Behavior
- The function first loads the JSON data from the file at
file_path
. - It then updates the value at the specified
json_path
using theset_json_value
function. - Finally, it saves the updated data back to the JSON file using the
save_json
function.
Error Handling
- If the JSON file does not exist or contains invalid JSON, it will create or overwrite the file with the new structure.
- If the path does not exist in the data, the function will create the necessary nested structure and set the value.