Reputation: 5
I'm trying to learn API's and I have a call to http://api.zippopotam.us/us/90210 which yields:
{"post code": "90210", "country": "United States", "country abbreviation": "US", "places": [{"place name": "Beverly Hills", "longitude": "-118.4065", "state": "California", "state abbreviation": "CA", "latitude": "34.0901"}]}
The API uses country (US) and zip code to return the "place". I tried to parse the "place" segment to a variable like so:
for item in api_return:
place = item['place']
However, I get an error message saying "TypeError: String indices must be integers"`. Is there another way to parse this long list to extract the "place name", "state" etc.?
Thanks in advance!
Upvotes: 0
Views: 1481
Reputation: 86
Quoting from this answer: https://stackoverflow.com/a/3294899/3474873
for key in d
: will simply loop over the keys in the dictionary, rather than the keys and values. To loop over both key and value you can use the following:
for key, value in d.iteritems():
Have a look at the actual answer if you are using Python 3.x as there are some slight differences.
Now in your case. First of all there is no key named "place"
in api_return
. Even if you had it right you would have still got an error.
If you need to access all the data then the simplest way is to include an if statement inside the for loop to check all the keys as below:
for key, value in d.iteritems():
if (key == "places"):
places = value
elif ...
If you only need one value, then you can skip the for loop and simply run:
places = api_return['places']
Both of the shown snippets will return the inner array contained inside api_return['places']
and store it in places
, where places[0]
is another dictionary and can be explored just like above.
EDIT :
To avoid confusion, you do also need to parse the received string using json
, just like mightyKeyboard has shown below.
Upvotes: 1
Reputation: 27
import json
data_str = '{"post code": "90210", "country": "United States", "country abbreviation": "US", "places": [{"place name": "Beverly Hills", "longitude": "-118.4065", "state": "California", "state abbreviation": "CA", "latitude": "34.0901"}]}'
data_json = json.loads(data_str)
for item in data_json['places']:
print item['place name']
#you can access the 'places' key-vals via the following, but
#it's not that pretty
print data_str['places'][0]['place name']
Upvotes: 0