Skip to main content

Read Value from JSON File

Description

The read_json_value function reads a value from a JSON file using a specified path. It loads the JSON data from the file and then retrieves the value from the data using the provided path.

Function Signature:

def read_json_value(file_path: str, json_path: str) -> Any:

Parameters

  • file_path (str): The full path to the JSON file to be read.
  • json_path (str): A dot-separated string representing the path to the value within the JSON structure (e.g., "user.profile.name").

Returns

  • Any: Returns the value at the specified path in the JSON file, or None if the path does not exist.

Example Usage

file_path = "/path/to/data.json"
json_path = "user.profile.name"
value = read_json_value(file_path, json_path)
print(value) # Output: "Jane" (if the value exists in the file)

Behavior

  • The function first loads the JSON data from the specified file.
  • It then uses the get_json_value function to retrieve the value at the specified path.

Error Handling

  • If the JSON file does not exist or contains invalid JSON, it will return an empty dictionary or None.
  • If the path does not exist in the data, it will return None.