skip to Main Content

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


  1. 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

    for key in json_object:
        if "EMR" in json_object[key]:
            json_object[key]["EMR"] = "CHANGED"
    

    And now you can print the updated json object

    print(json.dumps(json_object, indent = 1))
    

    enter image description here

    Login or Signup to reply.
  2. You can just iterate over the values, check if the value (assumed to be a dictionary) contains ‘EMR’ then update accordingly:

    import json
    
    stringJson = '{"TX1":{"EMR":"XSHGJ","ID":"200"},"TX2":{"EMR":"POIUY","ID":"300"}}'
    
    d = json.loads(stringJson)
    
    for v in d.values():
        if 'EMR' in v:
            v['EMR'] = 'CHANGED'
    
    print(json.dumps(d, indent=2))
    

    Output:

    {
      "TX1": {
        "EMR": "CHANGED",
        "ID": "200"
      },
      "TX2": {
        "EMR": "CHANGED",
        "ID": "300"
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search