dunkerkboy
dunkerkboy

Reputation: 63

Python http request and loop over contents of JSON

I'm trying to learn Python and have following problem: I get an error while running this as it cannot see the 'name' attribute in data. It works when I grab one by one items from JSON. However when I want to do it in a loop it fails. I assume my error is wrong request. That it cannot read JSON correctly and see attributes.

import requests
import json

def main():

    req = requests.get('http://pokeapi.co/api/v2/pokemon/')

    print("HTTP Status Code: " + str(req.status_code))
    print(req.headers)
    json_obj = json.loads(req.content)

    for i in json_obj['name']:
        print(i)

if __name__ == '__main__':
    main()

Upvotes: 1

Views: 4082

Answers (3)

Aquarthur
Aquarthur

Reputation: 619

A couple things: as soon mentioned, iterating through json_obj['name'] doesn't really make sense - use json_obj['results'] instead.

Also, you can use req.json() which is a method that comes with the requests library by default. That will turn the response into a dictionary which you can then iterate through as usual (.iteritems() or .items(), depending if you're using Python 2 or 3).

Upvotes: 0

Filip Happy
Filip Happy

Reputation: 624

Because all pokemons are saved in a list which is under keyword results, so you firstly need to get that list and then iterate over it.

for result in json_obj['results']:
print(result['name'])

Upvotes: 2

J L
J L

Reputation: 987

You want to access the name attribute of the results attribute in your json_object like this:

  for pokemon in json_obj['results']:
    print (pokemon['name'])

I was able to guess that you want to access the results keys because I have looked at the result of

json_obj.keys()

that is

dict_keys(['count', 'previous', 'results', 'next'])

Upvotes: 4

Related Questions