Reputation: 84
I'm using the Google Places Reverse Geocode API to return the latitude and longatude of a given address. The API returns a massive JSON file with tons of nested objects. Here's Google's documentation on it.
I'm trying to grab the geometry.location.lat object (see documentation). Here's my current code, followed by the error it returns:
address_coords = gmaps.geocode(raw_address)
# gmaps makes the API request and returns the JSON into address_coords
address_lat = address_coords['results']['geometry']['location']['lat']
address_lon = address_coords['results']['geometry']['location']['lng']
TypeError: List indices must be integers or slices, not str
I'm not sure how to reference that JSON object.
Upvotes: 0
Views: 167
Reputation: 91605
The error is telling you that you're trying to index an array as if it were a property.
Most likely results
is the array, so you'd need to do the following to get the value for the first item at index 0
:
address_coords['results'][0]['geometry']['location']['lng']
The other possibility is that geometry
contains multiple coordinates which you could similarly index:
address_coords['results']['geometry'][0]['location']['lng']
Either way, you should pretty print the structure to see which attributes are arrays versus dictionaries.
import pprint
pprint.pprint(address_coords)
Upvotes: 1