解析嵌套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
相关产品推荐
相关产品推荐

