Finds the path(s) to a given value in a JSON object. Args: json_obj (dict or list): The JSON object to search. target_value: The value to find in the JSON object. current_path (list): The current path being explored (used for recursion). Returns: list: A list of di
(json_obj, target_value, current_path=None)
| 94 | |
| 95 | |
| 96 | def find_json_path(json_obj, target_value, current_path=None): |
| 97 | """ |
| 98 | Finds the path(s) to a given value in a JSON object. |
| 99 | |
| 100 | Args: |
| 101 | json_obj (dict or list): The JSON object to search. |
| 102 | target_value: The value to find in the JSON object. |
| 103 | current_path (list): The current path being explored (used for recursion). |
| 104 | |
| 105 | Returns: |
| 106 | list: A list of dictionaries, each containing 'key_path' and 'value' for each occurrence of the target value. |
| 107 | """ |
| 108 | if current_path is None: |
| 109 | current_path = [] |
| 110 | |
| 111 | results = [] |
| 112 | |
| 113 | if isinstance(json_obj, dict): |
| 114 | for key, value in json_obj.items(): |
| 115 | new_path = current_path + [key] |
| 116 | if value == target_value: |
| 117 | results.append({ |
| 118 | 'key_path': new_path, |
| 119 | 'value': value |
| 120 | }) |
| 121 | if isinstance(value, (dict, list)): |
| 122 | results.extend(find_json_path(value, target_value, new_path)) |
| 123 | elif isinstance(json_obj, list): |
| 124 | for i, item in enumerate(json_obj): |
| 125 | new_path = current_path + [i] |
| 126 | if item == target_value: |
| 127 | results.append({ |
| 128 | 'key_path': new_path, |
| 129 | 'value': item |
| 130 | }) |
| 131 | if isinstance(item, (dict, list)): |
| 132 | results.extend(find_json_path(item, target_value, new_path)) |
| 133 | |
| 134 | return results |
| 135 | |
| 136 | |
| 137 |