Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
@dqharris6

This comment has been minimized.

Copy link

dqharris6 commented Apr 5, 2019

Is there any way to capture the position of the key that was found? I'm looking to pull the relative position of the key that was found, or somehow relate the data captured back to the structure of the original JSON.

@nikhilc2710

This comment has been minimized.

Copy link

nikhilc2710 commented Apr 6, 2019

thank you for this snippet greatly appreciated but when i trying to access key whole value is list or dict. it returning empty list
for ex extract_values(r.json,'rows')
it gives empty list

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.