Python JSON TypeError:列表索引必须是整数或切片,而不是字符串。

6

我目前试图解析 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 请求,一切都很顺利。


10
data['result']['results'] 是一个数组,因此您不能使用['name']。您需要一个整数,您可以在 ['name'] 之前添加 [0],这样就可以使用了。 - depperm
工作得非常完美,谢谢! - Matthewj
2
你可以通过迭代结果来实现,而不是添加 [0],以防有多个结果。 - Brian M. Sheldon
2个回答

21

data['result']['results'] 是一个数组,因此您无法使用 ['name'],您需要使用 int 类型,您可以在['results']后面添加 [0] ,这样就可以正常工作了。然后您就可以在 results 对象中引用键。


1
['results'] 后面的 [0] 应该保留,因为那是一个列表。 - Brian M. Sheldon
4
方括号 ([]) 表示 JSON 列表的起始和结束。列表需要使用数字索引。 - Brian M. Sheldon

1

在我的情况下:

    [
        {
            "_index": "abc",
            "_type": "abc",
            "_score": null,
            "_source": {
              "layers": {
                "frame_raw": [
                "frame": {
                ......
                "raw": [

访问“raw”值的正确方法是:

    data = json.load(json_file)
    data[0]['_source']['layers']['raw'][0]
    data[0]['_source']['layers']['raw'][1]
...

对于多个数据的情况:

    [
        {
            "_index": "abc",
            "_type": "abc",
            "_score": null,
            "_source": {
              "layers": {
                "frame_raw": [
                "frame": {
                ......
                "raw": [
{ "_index": "abc", "_type": "abc", "_score": null, "_source": { "layers": { "frame_raw": [ "frame": { ...... "raw": [

通过以下方式获取:

    data = json.load(json_file)
            for d in data:
                print(d['_source']['layers']['raw'][0])


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接