Skip to content

Instantly share code, notes, and snippets.

@mantig
Forked from toddbirchard/json_extract.py
Created August 8, 2019 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mantig/b2bd06ae5adca87c71326ebc7de3bd87 to your computer and use it in GitHub Desktop.
Save mantig/b2bd06ae5adca87c71326ebc7de3bd87 to your computer and use it in GitHub Desktop.
def extract_values(obj, key):
"""Recursively pull values of specified key from nested JSON."""
arr = []
def extract(obj, arr, key):
"""Return all matching values in an object."""
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
results = extract(obj, arr, key)
return results
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment