0

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

data.json

Note: in 'steps' list, the 3rd index did not return 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" 
        }
      ]
    }
  ], 
  "keyword": "Feature", 
  "name": "login", 
  "status": "passed"
}
]

What I want to achieve:

I want to insert a 'result' object if it is absent

[
{
  "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 Answer 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"}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.