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

解析嵌套JSON获取objectiveHash时遇TypeError问题求助

问题分析与解决

错误原因

你遍历JSON里的records字典时,默认只拿到了字典的键(字符串类型,比如"18302305"),而非键对应的记录对象。此时尝试用record['objectives']去访问字符串的"索引",自然触发TypeError: string indices must be integers——字符串只能用整数下标(比如record[0]),不能用字符串键。

修复代码

只需修改遍历方式,拿到records字典的**值(每个记录对象)**即可,用字典的.values()方法:

json_response = response.json()
# 遍历records字典的所有值(即每个包含objectives的记录对象)
for record in json_response['Response']['records']['data']['records'].values():
    objectives = record['objectives']
    for obj in objectives:
        hash_id = str(obj['objectiveHash'])
        # 这里可以添加处理hash_id的逻辑,比如打印或存储
        print(hash_id)

如果需要同时获取记录的ID(比如"18302305")和对应对象,可以用.items()方法:

json_response = response.json()
for record_id, record in json_response['Response']['records']['data']['records'].items():
    objectives = record['objectives']
    for obj in objectives:
        hash_id = str(obj['objectiveHash'])
        print(f"记录ID: {record_id}, ObjectiveHash: {hash_id}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 00:12:34