我调用了各种API端点来返回复杂程度各异的响应对象,并且我需要解析列表和/或字典的未知级别的嵌套数据结构。
例如,如果我返回响应并将json转换为此处的字典:
response = {
"key1":"value1",
"key2":"value2",
"key3":"value3",
"key4":[
"item1",
"item2"
],
"key5":"value4",
"key6":"value5",
"key7":{
"key1":"value1",
"key2":"value2",
"key3":"value3",
"key4":"value4",
"key5":"value5",
"key6":"value6"
},
"key8":"value6"
}
下面的我的方法将起作用,因为它仅处理嵌套深一层的列表或字典:
def check_values(payload):
values = []
for value in payload.values():
if isinstance(value, list):
for item in value:
values.append(bool(item))
elif isinstance(value, dict):
for nested_value in value.values():
values.append(bool(nested_value))
else:
values.append(bool(value))
if all(values):
return True
return False
print(check_values(response))
但是,如果我有类似的东西,我上面的方法将无法工作:
response = {
"key1": {"foobar" : ["a", None, {"xyz": 123}]},
"key2":"value2",
"key3":"value3",
"key4":[
[4, 5, 6],
[[[[[[[[[[[[[[[[[[[["hi"]]]]]]]]]]]]]]]]]]]]
],
"key5":"value4",
"key6":"value5",
"key7":{
"key1":"value1",
"key2":"value2",
"key3":"value3",
"key4":"value4",
"key5":"value5",
"key6":"value6"
},
"key8":"value6"
}
任何想法或建议将不胜感激。 =)
答案 0 :(得分:1)
.myDiv