You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python读取JSON遇TypeError,如何获取response['choices']['text']?

解决TypeError: list indices must be integers or slices, not str错误

错误原因

response['choices']是列表类型(JSON中[]包裹的结构对应Python的list),你直接对列表使用字符串索引['text'],这不符合列表的索引规则(列表只能用整数或切片作为索引),因此触发了类型错误。

正确获取text字段的方法

方法1:针对单个元素的场景

从你的JSON数据来看,choices列表仅包含1个元素,直接通过索引访问该元素后再提取text:

print(response['choices'][0]['text'])

方法2:针对多个元素的场景

如果后续choices可能包含多个元素,可通过循环遍历获取每个元素的text:

for choice in response['choices']:
    print(choice['text'])

内容的提问来源于stack exchange,提问作者Wesley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 19:00:59