您可以创建两个函数:一个用于展望和确定用户是否失败,另一个用于遍历整个结构的主函数:
def lookahead(d):
if isinstance(d, str):
return d == 'passed'
if all('outcome' in b for b in d.values()):
return all(b["outcome"] == "passed" for b in d.values())
return all(lookahead(b) for b in d.values())
def new_struct(d):
return [{'node_name':a, 'outcome':['failed', 'pass'][lookahead(b)] if isinstance(b, dict) and 'outcome' not in b else b['outcome'], 'children':[] if not isinstance(b, dict) or 'outcome' in b else new_struct(b)} for a, b in d.items()]
import json
d = {'scenario': {'server': {'testsuit_1': {'test_get': {'outcome': 'passed'}, 'test_set': {'outcome': 'failed'}}, 'testsui_2': {'test_get': {'outcome': 'passed'}, 'test_set': {'outcome': 'passed'}}}, 'client': {'test_receive': {'outcome': 'pass'}, 'test_send': {'outcome': 'fail'}}}}
print(json.dumps(new_struct(d), indent=4))
输出:
[
{
"node_name": "scenario",
"outcome": "failed",
"children": [
{
"node_name": "server",
"outcome": "failed",
"children": [
{
"node_name": "test_1",
"outcome": "failed",
"children": [
{
"node_name": "get",
"outcome": "passed",
"children": []
},
{
"node_name": "set",
"outcome": "failed",
"children": []
}
]
},
{
"node_name": "test_2",
"outcome": "pass",
"children": [
{
"node_name": "get",
"outcome": "passed",
"children": []
},
{
"node_name": "set",
"outcome": "passed",
"children": []
}
]
}
]
},
{
"node_name": "client",
"outcome": "failed",
"children": [
{
"node_name": "receive",
"outcome": "pass",
"children": []
},
{
"node_name": "send",
"outcome": "fail",
"children": []
}
]
}
]
}
]