Home > Enterprise >  How to add a new key-value pair to each object in a JSON array
How to add a new key-value pair to each object in a JSON array

Time:03-16

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.

CodePudding user response:

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}]
  • Related