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

为何出现TypeError: string indices must be integers错误?求代码修正与解释

错误原因分析

TypeError: string indices must be integers 意味着你试图用字符串("targetCeList")作为索引去访问一个字符串类型的变量。

回到你的代码:

  • json.loads(response.body_as_unicode()) 解析后得到的result,要么本身是一个字符串,要么是一个元素全为字符串的列表。
  • 当你用for r in result遍历时,如果result是字符串,r会被拆成单个字符(比如result="abc",遍历后r依次是"a"、"b"、"c");如果result是字符串列表,r就是列表里的单个字符串。
  • 不管哪种情况,r都是字符串,而字符串只能用整数下标(比如r[0])访问字符,用r["targetCeList"]自然会触发错误。
修正方案

首先要明确接口返回的JSON结构,你可以先打印result的类型和内容来确认:

def parse(self, response):
    result = json.loads(response.body_as_unicode())
    # 先打印结构,确认数据格式
    print("result类型:", type(result))
    print("result内容:", result)

根据实际结构调整代码:

  1. 如果接口返回的是单个字典(比如{"targetCeList": [...]}):
def parse(self, response):
    result = json.loads(response.body_as_unicode())
    # 直接从顶层字典取值
    name = result["targetCeList"]
    print(name)
  1. 如果接口返回的是字典列表(比如[{"targetCeList": ...}, {"targetCeList": ...}]):
def parse(self, response):
    result = json.loads(response.body_as_unicode())
    # 遍历列表,每个元素是字典
    for r in result:
        # 先判断当前元素是否为字典且包含目标键,避免报错
        if isinstance(r, dict) and "targetCeList" in r:
            name = r["targetCeList"]
            print(name)
  1. 如果result确实是字符串或字符串列表,那说明接口返回的JSON结构和你预期不符,需要核对接口文档或返回数据,调整解析逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 02:10:57