Python解析嵌套JSON遇TypeError,如何获取嵌套id值?
如何从嵌套JSON中正确获取'id'值?
问题中的JSON数据
{ "result": [ { "total": 142250, "_id": "BC", "test": [ { "id": "sample" } ] }, { "total": 210.88999999999996, "_id": "USD" }, { "total": 1065600, "_id": "TK" } ] }
错误代码及报错信息
错误代码
response = response.replace("'", '"') response = json.loads(response) for doc in response['result']: print(doc['_id'], doc['total']) docs = response['result'] for doc1 in docs['test']: print(doc1['id'])
报错信息
Traceback (most recent call last): File "./prog.py", line 34, in <module> TypeError: list indices must be integers or slices, not str
问题原因
response['result']是一个列表,不能直接通过docs['test']访问键值对;同时不是所有result中的对象都包含test字段,直接访问会触发报错。必须遍历列表内的每个对象,再判断是否存在目标字段后取值。
修正后的代码
import json # 假设response是你的原始JSON字符串 response = '''{ "result": [ { "total": 142250, "_id": "BC", "test": [ { "id": "sample" } ] }, { "total": 210.88999999999996, "_id": "USD" }, { "total": 1065600, "_id": "TK" } ] }''' response = response.replace("'", '"') data = json.loads(response) # 遍历result列表中的每个对象 for doc in data['result']: print(doc['_id'], doc['total']) # 判断当前对象是否包含test字段 if 'test' in doc: # test本身也是列表,遍历其中元素获取id for item in doc['test']: print(item['id'])
代码说明
- 先遍历
data['result']中的每一个字典对象,打印_id和total - 用
'test' in doc判断当前对象是否存在test字段,避免键不存在引发的报错 - 若存在
test字段,因它本身是列表,继续遍历其中元素取出嵌套的id值
内容的提问来源于stack exchange,提问作者user3004443
相关产品推荐
相关产品推荐

