Last active
September 6, 2023 04:40
-
-
Save toddbirchard/b6f86f03f6cf4fc9492ad4349ee7ff8b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Extract nested values from a JSON tree.""" | |
def json_extract(obj, key): | |
"""Recursively fetch values from nested JSON.""" | |
arr = [] | |
def extract(obj, arr, key): | |
"""Recursively search for values of key in JSON tree.""" | |
if isinstance(obj, dict): | |
for k, v in obj.items(): | |
if isinstance(v, (dict, list)): | |
extract(v, arr, key) | |
elif k == key: | |
arr.append(v) | |
elif isinstance(obj, list): | |
for item in obj: | |
extract(item, arr, key) | |
return arr | |
values = extract(obj, arr, key) | |
return values |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Super useful function, thanks all. Here's @Fjurg 's code with added type hinting and more explicit parameter names