Get Value from Nested JSON
Description
The get_json_value
function retrieves a value from a nested dictionary (JSON-like structure) using a dot-separated path. This function is useful for accessing deeply nested keys without needing to write repetitive code.
Function Signature:
def get_json_value(data: dict, path: str) -> Any:
Parameters
- data (dict): The dictionary (or JSON-like structure) from which to retrieve the value.
- path (str): A dot-separated string representing the path to the desired value (e.g.,
"user.profile.name"
).
Returns
- Any: The value located at the provided path. If the path is invalid (i.e., any part of the path is missing or not a dictionary), it returns
None
.
Example Usage
data = {"user": {"profile": {"name": "John", "age": 30}}}
value = get_json_value(data, "user.profile.name")
print(value) # Output: John
Behavior
- The function splits the provided path into keys and iteratively accesses each key in the dictionary.
- If any key is not found or if the current level of the data is not a dictionary, the function returns
None
.
Error Handling
- KeyError: The function silently returns
None
if any part of the path is invalid or missing. - TypeError: The function returns
None
if the structure at any key is not a dictionary.