Search code examples
pythonjsonapietsy

Parsing Multiple json elements in python


I'm trying to build a small script that will go through the Etsy API and retrieve certain information. The API returns 25 different listing all in json and I would appreciate it if someone could help me learn how to handle one at a time.

Here is an example of the json I'm dealing with:

{"count":50100,"results":[{"listing_id":114179207,"state":"active"},{"listing_id":11344567,"state":"active"},

and so on.

Is there a simple way to handle only one of these listings at a time to minimize the amount of calls I must make to the API?

Here is some of the code of how I'm dealing with just one when I limit the results returned to 1:

r = requests.get('http://openapi.etsy.com/v2/listings/active?api_key=key&limit=1&offset='+str(offset_param)+'&category=Clothing')
raw_json = r.json()
encoded_json = json.dumps(raw_json)
dataObject = json.loads(encoded_json)
if dataObject["results"][0]["quantity"] > 1:
    if dataObject["results"][0]["listing_id"] not in already_done:
        already_done.append(dataObject["results"][0]["listing_id"])
        s = requests.get('http://openapi.etsy.com/v2/users/'+str(dataObject["results"][0]["user_id"])+'/profile?api_key=key')
        raw_json2 = s.json()
        encoded_json2 = json.dumps(raw_json2)
        dataObject2 = json.loads(encoded_json2)

        t = requests.get('http://openapi.etsy.com/v2/users/'+str(dataObject["results"][0]["user_id"])+'?api_key=key')
        raw_json3 = t.json()
        encoded_json3 = json.dumps(raw_json3)
        dataObject3 = json.loads(encoded_json3)

Solution

  • Seeing how the results field (or key) contains a list structure, you can simply iterate it through like the following

    json_str = { ...other key-values, "results": [{"listing_id":114179207,"state":"active"},{"listing_id":11344567,"state":"active"}, ...and so on] }
    results = json_str['results']  # this gives you a list of dicts
    
    # iterate through this list
    for result in results:
        if result['state'] == 'active':
            do_something_with( result['listing_id']
        else:
            do_someotherthing_with( result['listing_id']  # or none at all