Python/Django引用嵌套的JSON

2024-06-02 05:07:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用googleplaces反向地理编码API返回给定地址的纬度和长度。API返回一个包含大量嵌套对象的大量JSON文件。这是谷歌的documentation。你知道吗

我想抓住几何.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对象。你知道吗


Tags: the对象apijson编码address地址location
1条回答
网友
1楼 · 发布于 2024-06-02 05:07:57

这个错误告诉您,您试图将数组作为属性来索引。你知道吗

最有可能的results是数组,因此需要执行以下操作以获取索引0处第一项的值:

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

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

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

不管是哪种方式,您都应该漂亮地打印结构,以查看哪些属性是数组还是字典。你知道吗

import pprint

pprint.pprint(address_coords)

相关问题 更多 >