我有一个数据库,用于存储每个API调用的请求和响应数据(即JSON)。我的目的是找出响应数据中是否存在关键的“ errorCode”,以找出有多少次错误返回。
从数据库提取的数据是JSON字符串。 我使用JSON.loads()将其转换为python字典。 现在,我唯一想做的就是遍历字典以找到我的键“ errorCode”。这是我需要帮助的地方。
我有2个函数,用于在字典上进行递归迭代,并在列表中进行迭代(如果列表在字典中)。
使用的JSON:
{\"Errors\":{\"Number\":null,\"error\":[{\"errorCode1234\":\"NS-38\",\"errorDescription\":\"Some Error Desc\"}]}}
JSON.loads()成功解析了这一点。
迭代字典的功能:
def iterdict2(response_dict):
for key, value in response_dict.items():
if key == 'errorCode':
print("KEY FOUND")
print(value)
return value
elif isinstance(value, dict):
iterdict2(value)
elif isinstance(value, list):
iterlist2(value)
在我的字典中遍历列表的功能:
def iterlist2(inner_list):
for item in inner_list:
if isinstance(item, dict):
iterdict2(item)
else:
iterlist2(item)
主要代码:
json_dict = json.loads(json_string)
print("Printing")
val = iterdict2(json_dict)
print(val)
如果是JSON,则找不到键“ errorCode”,然后函数不返回任何内容。结果是
TypeError: cannot unpack non-iterable NoneType object.
如何处理这种情况。 添加其他不起作用。
任何帮助将不胜感激!