如何遍历JSON嵌套对象?解决'dict' object is not callable报错
解决嵌套字典键遍历的错误问题
问题重现
你处理的JSON片段:
{"id":"2769","data":{"accommodation":{"town":"Dublin","addressYears":1,"postcode":"K12 Y453","accommodationType":"select"},"bankDetails":{"payee":"Name","Number":"1234567890"},"creditReport":{"creditReportMessageId":"message id","creditReportContractCode":"contact code","creditReportSource":"cccs"},"dependents":{"dependentsCount":0,"dependentsCount2":0}}}
你尝试的遍历代码:
for i in data: print(i) for j in data[i]: print(j) for k in data(j): print(k)
运行时出现错误:
'dict' object is not callable
错误原因
第三层循环里的data(j)是错误写法:Python中字典的元素访问必须用方括号[],而括号()是用来调用函数的。这里data是字典对象,不是可调用的函数,因此触发该错误。此外,你要遍历的是第二层字典(比如data[i]对应的accommodation字典)的子键,第三层应该遍历data[i][j]的键。
修正后的代码
假设你已经将JSON字符串解析为Python字典(用json.loads()),修正后的遍历代码如下:
import json # 解析JSON字符串 json_content = '{"id":"2769","data":{"accommodation":{"town":"Dublin","addressYears":1,"postcode":"K12 Y453","accommodationType":"select"},"bankDetails":{"payee":"Name","Number":"1234567890"},"creditReport":{"creditReportMessageId":"message id","creditReportContractCode":"contact code","creditReportSource":"cccs"},"dependents":{"dependentsCount":0,"dependentsCount2":0}}}' parsed_data = json.loads(json_content) data = parsed_data['data'] # 修正后的三层循环 for first_key in data: print(first_key) second_dict = data[first_key] for second_key in second_dict: print(f" {second_key}") third_dict = second_dict[second_key] for third_key in third_dict: print(f" {third_key}")
运行后会按层级输出所有键:
accommodation town (无第三层,对应值为字符串) addressYears ... postcode ... accommodationType ... bankDetails payee ... Number ... ...
更通用的递归遍历方案
如果JSON的嵌套层级不确定,递归方法能更灵活地处理所有层级的键:
def traverse_nested_keys(dictionary, indent=0): for key in dictionary: print(" " * indent + key) value = dictionary[key] # 如果当前值还是字典,继续递归遍历 if isinstance(value, dict): traverse_nested_keys(value, indent + 1) # 调用函数遍历所有层级键 traverse_nested_keys(data)
这个方法会自动识别嵌套字典,逐层打印所有键,无需手动编写多层循环。
内容的提问来源于stack exchange,提问作者Jordan121
相关产品推荐
相关产品推荐

