我目前试图解析 POST 请求响应中的一些数据,但是我一直收到这个错误:“TypeError: list indices must be integers or slices, not str”。
Python 代码
import requests
import json
count = 0
params = {'var1':'40', 'value':'143', 'itm':'1', 'param':'1'}
req = 'https://www.api.com/api/search'
data = requests.post(req, data = params).json()
print (data['result']['results']['name'])
JSON响应
{
"result":{
"count":1,
"totalCount":1,
"offset":0,
"queryTime":232,
"results":[
{
"rating":"4.0",
"productId":{
"upc":"143",
"ItemId":"143",
"productId":"143-prd"
},
"name":"Product",
"catagory":{
"name":"",
"CataId":1
},
"images":{
"thumbnailUrl":"http://api.com/img/static/product-image-50-50.png",
"largeUrl":"http://api.com/img/static/product-image-500-500.png"
},
"price":{
"price":13,
"isRealTime":true,
"currencyUnit":"USD"
},
"location":{
"unit":[],
"detailed":[]
},
"inventory":{
"quantity":1,
"status":"In Stock",
"isRealTime":true
},
"ratings":{
"rating":"3.1875",
"ratingUrl":"http://api.com/3_1875.gif"
},
"reviews":{
"reviewCount":"2"
},
"isItem":true,
"lUrl":"/l/Product-Name"
}
],
"performance":{
"enrichment":{
}
},
"query":{
"originalQuery":"143",
"actualQuery":"143",
"suggestedQueries":[
]
},
"algo":"jarvis",
"blacklist":false,
"cluster":{
"apiserver":{
"hostname":"site.api.com",
"pluginVersion":"1.0"
},
"searchengine":{
"hostname":"srch.site.api.com"
}
}
}
}
我写了一段类似的代码,但是它是一个 GET 请求,一切都很顺利。
data['result']['results']
是一个数组,因此您不能使用['name']
。您需要一个整数,您可以在['name']
之前添加[0]
,这样就可以使用了。 - depperm[0]
,以防有多个结果。 - Brian M. Sheldon