Python列表索引必须是整数或片,而不是str

2024-10-01 13:44:39 发布

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

假设我的json响应如下所示:

{
  "classifier_id" : "12345",
  "url" : "https://something.com",
  "text" : "text",
  "top_class" : "class1",
  "classes" : [ {
    "class_name" : "car",
    "confidence" : 0.9862312904583641
  }, {
    "class_name" : "bus",
    "confidence" : 0.013768709541636032
  } ]
}

底层GET请求为

callIBM = requests.get(
    url="https://something.com",
    params={
        "text": update.message.text,
    },
    headers={
        "Authorization": "XXX",
    },
)

我想用python解析结果

我试过:

ibmscore1 = '{}'.format(callIBM.json()["classes"][0]["class_name"]["confidence"])
ibmscore2 = '{}'.format(callIBM.json()["classes"][1]["class_name"]["confidence"])

但它不起作用。能不能请一位Python新手帮忙


Tags: textnamehttpscomidjsonformaturl
1条回答
网友
1楼 · 发布于 2024-10-01 13:44:39

您正试图访问class_name内的confidence,但class_name不是字典

尝试:

resp = callIBM.json()
class1, conf1 = resp["classes"][0]["class_name"], resp["classes"][0]["confidence"]
class2, conf2 = resp["classes"][1]["class_name"], resp["classes"][0]["confidence"]

相关问题 更多 >