Python如何在嵌套列表中插入对象

时间:2017-01-06 17:14:05

标签: python json

如何在嵌套列表中插入对象。我得到的json响应没有为某个条件返回某个对象

data.json

注意:在“步骤”列表中,第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"
}
]

我想要实现的目标:

我想插入'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"
}
]

到目前为止我做了什么(伪):

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 个答案:

答案 0 :(得分:2)

以下内容应该为您说明:

for step in data[0]['elements'][0]['steps']:
    if 'result' not in step:
        step['result'] = {"status": "skipped"}

更通用的解决方案:

for d in data:
    for element in d['elements']:
        for step in element['steps']:
            if 'result' not in step:
                step['result'] = {"status": "skipped"}