How do I insert an object in nested lists. I get json response that doesn't return a a certain object for certain a condition
如何在嵌套列表中插入对象。我得到了json响应,它不会为某个条件返回某个特定对象
data.json
data.json
Note: in 'steps' list, the 3rd index did not return result
注意:在'steps'列表中,第3个索引没有返回结果
[
{
"elements": [
{
"keyword": "Scenario",
"name": "valid user can login site",
"steps": [
{
"name": "a valid user name and password",
"result": {
"status": "passed"
}
},
{
"name": "a valid user clicking on the login button after typing in user name and password",
"result": {
"status": "passed"
}
},
{
"name": "map should display"
}
]
}
],
"keyword": "Feature",
"name": "login",
"status": "passed"
}
]
What I want to achieve:
我想要实现的目标:
I want to insert a 'result' object if it is absent
如果不存在,我想插入'result'对象
[
{
"elements": [
{
"keyword": "Scenario",
"name": "valid user can login site",
"steps": [
{
"name": "a valid user name and password",
"result": {
"status": "passed"
}
},
{
"name": "a valid user clicking on the login button after typing in user name and password",
"result": {
"status": "passed"
}
},
{
"name": "map should display"
"result": {
"status": "skipped"
}
}
]
}
],
"keyword": "Feature",
"name": "login",
"status": "passed"
}
]
What i've done so far (pseudo):
到目前为止我做了什么(伪):
with open('data.json') as data_file:
data = json.load(data_file)
#nested for loops??
#if x.has_key('result') == False
#insert result object
1 个解决方案
#1
2
The following should word for you:
以下应该告诉你:
for step in data[0]['elements'][0]['steps']:
if 'result' not in step:
step['result'] = {"status": "skipped"}
More generic solution:
更通用的解决方案
for d in data:
for element in d['elements']:
for step in element['steps']:
if 'result' not in step:
step['result'] = {"status": "skipped"}
#1
2
The following should word for you:
以下应该告诉你:
for step in data[0]['elements'][0]['steps']:
if 'result' not in step:
step['result'] = {"status": "skipped"}
More generic solution:
更通用的解决方案
for d in data:
for element in d['elements']:
for step in element['steps']:
if 'result' not in step:
step['result'] = {"status": "skipped"}