Skip to content

Instantly share code, notes, and snippets.

@mrAndreyIsachenko
Forked from toddbirchard/json_extract.py
Created November 30, 2021 17:40
Show Gist options
  • Select an option

  • Save mrAndreyIsachenko/d06a4af6b671e876bb70e02177da2357 to your computer and use it in GitHub Desktop.

Select an option

Save mrAndreyIsachenko/d06a4af6b671e876bb70e02177da2357 to your computer and use it in GitHub Desktop.
"""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