试图从python中的json文件解析href
我有一个程序,我想从GooglePlacesAPI收集单个数据片段。我能够获得我想要的大多数属性,但是,当我尝试获取“html_属性”时,我会得到以下错误:试图从python中的json文件解析href,json,python-2.7,parsing,google-places-api,Json,Python 2.7,Parsing,Google Places Api,我有一个程序,我想从GooglePlacesAPI收集单个数据片段。我能够获得我想要的大多数属性,但是,当我尝试获取“html_属性”时,我会得到以下错误: TypeError: list indices must be integers, not str 我对这一行使用了与其他行相同的格式,所以我不明白它为什么会抛出这个错误 这是我的代码: for n in range(len(data['results'])): location = []
TypeError: list indices must be integers, not str
我对这一行使用了与其他行相同的格式,所以我不明白它为什么会抛出这个错误
这是我的代码:
for n in range(len(data['results'])):
location = []
address = data['results'][n]['vicinity']
address = address[: address.rfind(", ")]
coords_lat = str(data['results'][n]['geometry']['location']['lat'])
coords_lng = str(data['results'][n]['geometry']['location']['lng'])
url_href = ''
if str(data['results'][n]['photos']['html_attributions']):
url_href = str(data['results'][n]['photos']['html_attributions'])
location = [address, coords_lat, coords_lng, url_href]
return location
这是JSON数据:
{
"geometry" : {
"location" : {
"lat" : 43.3151516,
"lng" : -79.9131046
},
"viewport" : {
"northeast" : {
"lat" : 43.31669727989272,
"lng" : -79.91206752010727
},
"southwest" : {
"lat" : 43.31399762010727,
"lng" : -79.91476717989272
}
}
},
"icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/shopping-71.png",
"id" : "d66fce15477e5e481e618cdf7483809c6581060c",
"name" : "Two Men & A Truck",
"opening_hours" : {
"open_now" : true,
"weekday_text" : []
},
"photos" : [
{
"height" : 667,
"html_attributions" : [
"\u003ca href=\"https://maps.google.com/maps/contrib/116914873550616940396/photos\"\u003eTwo Men and A Truck\u003c/a\u003e"
],
"photo_reference" : "CmRaAAAANR4eDG2XMLwt16x9WXQNPH45QExLrJOmBUaHYF2lNXejPRGm6G1D8WT6EhVDruj8SHkNjRwmE_BcwavNs0Olq2PJveNVFG9GFKtXoBzF1w9JLjTKZiEFxmKZho-mvTPJEhCXKgV1x1fFgzcOYasfGnjzGhQ9gezZ8T16Qyogf9CTS4OiSrpK1g",
"width" : 1024
}
],
"place_id" : "ChIJ510ZCi6dLIgRYNowStOOqxQ",
"rating" : 2,
"reference" : "CmRbAAAAU36QBuW3xN3We55B8WvA_6OAFkMJx-dS2u0REb8xFjdqxkRjQe4kIlSwx1lvu9DL8GIckgpT_pspgN618vJF06m4BZZ-pwG8gIllEHHmjhCSXX44PmeOXKeBirjeHHSJEhBKlLGuJ3HrpwKj1DnYqWpSGhSLQhCw8j3ercmdZS-c_bHNZ-BnOA",
"scope" : "GOOGLE",
"types" : [ "car_repair", "store", "point_of_interest", "establishment" ],
"vicinity" : "50 Dundas St E, Dundas"
}
从查看有效负载到获取“html_属性”,假设您的解析数据['results'][n]正确(因为您没有显示整个json有效负载),您必须执行以下操作
data['results'][n]['photos'][0]['html_attributions'][0]
我们可以看到包含“html_Attributes”键的“data”有效负载吗?我猜您解析的有效负载稍有错误。只是添加了JSON数据。这就是您要查找的吗?仔细看看您的JSON数据-在“photos”元素中有一个列表,这就是为什么“html_Attributes”不是子元素的原因。如果我添加了str(data['results')[n] ['photos'[1]]),应该这样做吗?或者我如何从“html_属性”中获取数据?