
本文详解 python 中解析深层嵌套 json 时因误将字典键当值使用而导致 `typeerror: string indices must be integers` 的根本原因,并提供两种标准解决方案:使用 `.values()` 获取纯值,或用 `.items()` 同时获取键与值。
在处理类似 Destiny 2 API 返回的嵌套 JSON 数据时,一个常见误区是:当目标字段(如 "records")实际是一个字典(dict)而非列表(list)时,直接对它进行 for record in ... 迭代,得到的其实是每个记录的键(如 "18302305"、"100144154" 等字符串),而非对应的记录对象本身。这正是报错 TypeError: string indices must be integers 的根源——代码试图用字符串 'objectives' 去索引一个字符串(比如键 "18302305"),而 Python 只允许用整数索引字符串(如 "abc"[0]),于是抛出异常。
✅ 正确做法是明确指定遍历字典的值或键值对:
✅ 方案一:只取值(推荐,若无需记录 ID)
json_response = response.json()
records_dict = json_response['Response']['records']['data']['records']
for record in records_dict.values(): # ← 关键:.values() 返回所有 record 对象(字典)
objectives = record.get('objectives', [])
for obj in objectives:
hash_id = obj.get('objectiveHash')
if hash_id is not None:
print(f"Objective Hash: {hash_id}")✅ 方案二:同时获取键与值(若需关联 record ID)
for record_id, record in records_dict.items(): # ← .items() 返回 (key, value) 元组
objectives = record.get('objectives', [])
for obj in objectives:
hash_id = obj.get('objectiveHash')
if hash_id is not None:
print(f"Record {record_id} → Objective Hash: {hash_id}")? 关键提醒:
- 始终用 .get(key, default) 替代直接索引(如 record['objectives']),避免 KeyError;
- objectives 字段可能为空列表或缺失,务必做存在性检查;
- 嵌套层级深(如 ['Response']['records']['data']['records'])建议分步赋值并添加类型/存在性校验,提升可读性与健壮性;
- 可借助 pprint 或 json.dumps(..., indent=2) 快速查看结构,确认 records 确为字典而非列表。
通过明确区分字典的「键迭代」与「值迭代」,即可安全、高效地从复杂嵌套 JSON 中精准提取所需字段。










