0

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)

1 Answer 1

0

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
3
  • So I could just iterate through dataObject just like that?
    – Heisenberg
    Commented Jul 19, 2013 at 14:51
  • As soon as you decoded JSON string into Python data structures (that is using json.loads() or requests.Response.json() as you do there), yes, you can iterate them just like that :)
    – woozyking
    Commented Jul 19, 2013 at 14:59
  • Wow that is almost too easy. Haha. Thank you for your help. I've got it working now.
    – Heisenberg
    Commented Jul 19, 2013 at 15:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.