2

How can I add a new key-value pair to each of the objects in a JSON array as shown below? I tried using the below code, but the result is separated instead of being in the same, original array.

import json

json_var = '''{
"information" : {
  "info_id"          : "8878",
  "info_name"        : "Stackoverflow"
},

"env" : {
  "env_name"           : "UAT",
  "env_type"           : "Staging"
},

"services" : [
  {
    "service_name"         : "stack1",
    "service_version"     : "1"
  },
  {
    "service_name"         : "stack2",
    "service_version"     : "2"
  },  
  {
    "service_name"         : "stack3",
    "service_version"     : "3"
  }
 ]
}'''

y = {"pin":110096}
entry = json.loads(json_var)

for i in entry['services']:
      i.update(y)
      print(json.dumps(i))

Actual output:

{"service_name": "stack1", "service_version": "1", "pin": 110096}
{"service_name": "stack2", "service_version": "2", "pin": 110096}
{"service_name": "stack3", "service_version": "3", "pin": 110096}

Expected output:

[
{"service_name": "stack1", 
  "service_version": "1", 
  "pin": 110096
},
{"service_name": "stack2",
 "service_version": "2",
 "pin": 110096
},
{"service_name": "stack3",
 "service_version": "3",
 "pin": 110096
}
]

Please advise on how to modify the above code or provide new code to achieve the expected output.

1 Answer 1

2

The only issue is with the placement of your print() statement. It should be outside of the for loop, and you should be printing entry['services'] rather than i. This allows you to print all of updated entries at once, rather than one at a time.

y = {"pin":110096}
entry = json.loads(json_var)

for i in entry['services']:
    i.update(y)

print(json.dumps(entry['services']))

This outputs:

[{"service_name": "stack1", "service_version": "1", "pin": 110096},
{"service_name": "stack2", "service_version": "2", "pin": 110096},
{"service_name": "stack3", "service_version": "3", "pin": 110096}]
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.