2017-08-04 100 views
0

我使用Google Places Reverse Geocode API返回给定地址的纬度和长度。该API返回一个庞大的JSON文件,其中包含大量嵌套对象。这里是Google的documentationPython/Django引用嵌套JSON

我想抓住geometry.location.lat对象(请参阅文档)。这里是我当前的代码,然后它会返回错误:

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

我不知道如何引用JSON对象。

+0

您应该显示您尝试访问的数据。如错误所述,该数据结构的至少一个级别是列表而不是字典。 –

回答

1

错误是告诉你,你正试图索引一个数组,就好像它是一个属性。

最有可能results是数组,所以你需要做以下的指数0获得的第一个项目的值:

address_coords['results'][0]['geometry']['location']['lng'] 

另一种可能性是,geometry包含多个坐标您可以类似地索引:

address_coords['results']['geometry'][0]['location']['lng'] 

无论哪种方式,你应该漂亮打印结构,看看哪些属性是数组与字典。

import pprint 

pprint.pprint(address_coords)