如何遍历嵌套 JSON 提取 objectiveHash 值
作者:小月亮
时间:2026-02-20
浏览:0
本文详解Python中解析深层嵌套JSON时因误将字典键当值使用而导致TypeError:stringindicesmustbeintegers的根本原因,并提供两种标准解决方案:使用.values()获取纯值,或用.items()同时获取键与值。

本文详解 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 中精准提取所需字段。
作者最新文章
纯纯写作
2026-09-16 17:42
JMeter入门:创建HTTP请求并验证响应结果
2026-09-02 10:20
文件表格制作教程:选择Word或Excel的判断方法
2026-09-02 09:45
多个PPT怎么一次性转PDF?PPT批量转换工具有哪些?
2026-09-02 06:00
PDF图纸转CAD的3种方法及比例校准指南
2026-09-01 18:36
上一篇:
iPhone 18 Pro首支持星链直连
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多


































