Input json : {"TX1":{ "EMR": "XSHGJ", "ID": "200", "SERIAL": "ZZZ001"},"TX2":{"EMR": "POIUY", "ID": "300", "SERIAL": "YYY001"}}
I want to update key’s value in Json, but when I’m trying to do it using below, its just adding new key-value
at end of json
import json
stringJson = '{"TX1":{"EMR":"XSHGJ","ID":"200"},"TX2":{"EMR":"POIUY","ID":"300"}}'
# convert string to object
json_object = json.loads(stringJson)
json_object["EMR"] = 'CHANGED'
print(json.dumps(json_object, indent = 1))
`
Getting output
{ "TX1": { "EMR": "XSHGJ", "ID": "200", "SERIAL": "ZZZ001" }, "TX2": { "EMR": "POIUY", "ID": "300", "SERIAL": "YYY001" }, "EMR": "CHANGED" }
but need output like
{ "TX1": { "EMR": "CHANGED", "ID": "200", "SERIAL": "ZZZ001" }, "TX2": { "EMR": "CHANGED", "ID": "300", "SERIAL": "YYY001" } }
May I know please, how can I Achieve this ?
2
Answers
I am assuming you need to change EMR key for all the root level keys. Like @Gugu72 said, the EMR key is nested so you need to run for loop for this
And now you can print the updated json object
You can just iterate over the values, check if the value (assumed to be a dictionary) contains ‘EMR’ then update accordingly:
Output: