我正在尝试从Python读取JSON。以下是从地理代码请求返回的JSON对象:
{
"results" : [
{
"address_components" : [
{
"long_name" : "Race Course Lane",
"short_name" : "Race Course Ln",
"types" : [ "route" ]
},
{
"long_name" : "Little India",
"short_name" : "Little India",
"types" : [ "neighborhood", "political" ]
},
{
"long_name" : "Singapore",
"short_name" : "Singapore",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Singapore",
"short_name" : "SG",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "Race Course Ln, Singapore",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 1.3103311,
"lng" : 103.85354
},
"southwest" : {
"lat" : 1.3091323,
"lng" : 103.8523656
}
},
"location" : {
"lat" : 1.3097033,
"lng" : 103.8529918
},
"location_type" : "GEOMETRIC_CENTER",
"viewport" : {
"northeast" : {
"lat" : 1.311080680291502,
"lng" : 103.8543017802915
},
"southwest" : {
"lat" : 1.308382719708498,
"lng" : 103.8516038197085
}
}
},
"place_id" : "ChIJe5XzBMcZ2jERclOJt-xVp_o",
"types" : [ "route" ]
}
],
"status" : "OK"
}
我试图得到格式化的地址和纬度lng下几何。这是我的密码:
json_data = requests.get(url).json()
formatted_address = json_data['results'][0]['formatted_address']
print(formatted_address)
for each in json_data['results'][0]['geometry']:
print(each['lat'])
我设法打印出格式化的地址,但收到以下错误消息:
Traceback (most recent call last):
File "D:\Desktop\test.py", line 16, in <module>
print(each['lat'])
TypeError:字符串索引必须是整数
有什么想法吗?谢谢!你知道吗
json_data['results'][0]['geometry']
是_dict_
。这意味着,for x in json_data['results'][0]['geometry']
将导致对键的迭代,其中x
是分配给键(字符串)的循环变量。举个例子-因为
each
是一个字符串,each['lat']
将是一个无效的操作(因为您不能用除整数之外的任何东西来索引字符串)观察JSON文件的结构-
仔细观察,只有
location
具有与之相关联的lat
和lng
键的dict。如果您只需要这些值,那么只需直接索引它们。不需要循环相关问题 更多 >
编程相关推荐