Ozzie Ghani Ozzie Ghani - 3 months ago 15
JSON Question

python json, replacing values with key and value pairs

in the following example I am trying to replace value of one key by the value of another key; but I tried multiple ways and it doesn't seem to work.

following is my code

d = {
"name" : "ABC",
"type" : "Service",
"clusterRef" : {
"clusterName" : "ABCSTUFF"
},
"serviceState" : "STARTED",
"healthChecks" : [ {
"name" : "STORAGE",
"summary" : "GOOD"
}, {
"name" : "CPU UTILIZATION",
"summary" : "GOOD"
} ],
"maintenanceMode" : "false"
}


########################
## Get Key Value

def get_key_values(d, key):
for k, v in d.items():
if k == "name":
k = (key + "." + v)
else:
k = (key + "." + k)
if isinstance(v, dict):
get_key_values(v, k)
elif isinstance(v, list):
for i in v:
get_key_values(i, k)
else:
print ("{0} : {1}".format(k, v))


get_key_values(d, "TTS")


the result come up like following


TTS.serviceState : STARTED
TTS.type : Service
TTS.ABC : ABC
TTS.clusterRef.clusterName : ABCSTUFF
TTS.healthChecks.summary : GOOD <<< remove this line and replace "Good" with the value for "TTS.healthChecks.STORAGE"
TTS.healthChecks.STORAGE : STORAGE
TTS.healthChecks.summary : GOOD <<< remove this line and replace "Good" with the value for "TTS.healthChecks.CPU UTILIZATION"
TTS.healthChecks.CPU UTILIZATION : CPU UTILIZATION
TTS.maintenanceMode : false



but I want the result to be following


TTS.serviceState : STARTED
TTS.type : Service
TTS.ABC : ABC
TTS.clusterRef.clusterName : ABCSTUFF
TTS.healthChecks.STORAGE : GOOD <<<
TTS.healthChecks.CPU UTILIZATION : GOOD <<<
TTS.maintenanceMode : false



Any help is much appreciated

BPL BPL
Answer

Here's a non-generic solution which works for your question:

d = {
    "name": "ABC",
    "type": "Service",
    "clusterRef": {
        "clusterName": "ABCSTUFF"
    },
    "serviceState": "STARTED",
    "healthChecks": [{
        "name": "STORAGE",
        "summary": "GOOD"
    }, {
        "name": "CPU UTILIZATION",
        "summary": "GOOD"
    }],
    "maintenanceMode": "false"
}


########################
# Get Key Value

def get_key_values(d, key):
    for k, v in d.items():
        if k == "name":
            k = (key + "." + v)
        else:
            k = (key + "." + k)

        if isinstance(v, dict):
            get_key_values(v, k)
        elif isinstance(v, list):
            for i in v:
                tok1 = k + "." + i.get("name")
                tok2 = i.get("summary")
                print("{0} : {1}".format(tok1, tok2))
        else:
            print("{0} : {1}".format(k, v))

get_key_values(d, "TTS")