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

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

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

@ecallahan5

This comment has been minimized.

Copy link

commented Jun 23, 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

Agreed. To be more specific, in my case it seems to return values fine when the key refers to a single text value but returns an empty list when the key refers to a value which is another dictionary.

@mantig

This comment has been minimized.

Copy link

commented Aug 8, 2019

Hello, i'm trying to parse through the json files from https://nvd.nist.gov/vuln/data-feeds.
Everything is deeply nested. I'll give this a try and see if it will work. Do you think there are any changes that i'll have to specify for it to work?
I just keep getting "CVE_items" as a column and a bunch of nested json data within the field.

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.