2017-08-04 98 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)