Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Goal

I've got some complex json data with nested data in it which I am retrieving from an API I'm working with. In order to pull out the specific values I care about, I've created a function that will pull out all the values for a specific key that I can define. This is working well to retrieve the values in a list, however I am running into an issue where I need to return multiple values and associate them with one another so that I can get each result into a row in a csv file. Currently the code just returns separate arrays for each key. How would I go about associating them together? I've messed with the zip function in Python but can't seem to get it working properly. I sincerely appreciate any input you can give me.

Extract Function

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

Main.py

res = requests.get(prod_url, headers=prod_headers, params=payload)

record_id = json_extract(res.json(), 'record_id')
status = json_extract(res.json(), 'status')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
4.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

The solution was simple....just use the zip function ex: zip(record_id, status)

I had a syntax error that was preventing it from working before.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...