Skip to content

Instantly share code, notes, and snippets.

@scarsman
Forked from toddbirchard/json_extract.py
Created May 10, 2019 10:42
Show Gist options
  • Select an option

  • Save scarsman/803a4e3ca6118cd38b745b0f40dab3f1 to your computer and use it in GitHub Desktop.

Select an option

Save scarsman/803a4e3ca6118cd38b745b0f40dab3f1 to your computer and use it in GitHub Desktop.

Revisions

  1. @toddbirchard toddbirchard created this gist Jan 22, 2019.
    19 changes: 19 additions & 0 deletions json_extract.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,19 @@
    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