1

I'm receiving json files improperly and am trying to create a temporary fix until the documents come in the proper format. Instead of the value being set to the derivationsValue key, it is being set as a key value pair, so there is an extraneous key. I want to set the the inner value to the outer key.

{        
  "derivationName": "other_lob_subcd",
  "derivationValue": {
     "OOP3": "TENANT"
  }
}

Given the above json, I want the result to be

{        
  "derivationName": "other_lob_subcd",
  "derivationValue": "TENANT"
}

I could also live with

{        
   "derivationName": "other_lob_subcd",
   "derivationValue": "OOP3-TENANT"
}

or something like that. It just can't be another json element.

Based on @Diana Ayala's answer, I have written this to try solving the problem with variable keys.

    for k,v in data['mcsResults']['derivationsOutput']:
        if isinstance(k['derivationValue'], dict):
            for sk, sv in k['derivationValue']:
                k['derivationValue'] = sv
RagePwn
  • 411
  • 2
  • 8
  • 22

3 Answers3

2

You can use below generic code for your requirement.

import json

filePath = 'file.json'

def getValue(value):
    if type(value) is dict:
        ans = list(value)[0]
        for k in value:
            ans += '-'+getValue(value[k])
        return ans
    return value

def correct(data):
    for key in data:   
        data[key] = getValue(data[key]) 
    return data

if __name__ == "__main__":
    with open(filePath) as fp:
        data = json.load(fp)
        data = correct(data)
        print (data)

output:

D:\>python file.py
{'derivationName': 'other_lob_subcd', 'derivationValue': 'OOP3-TENANT'}
Mayur
  • 2,583
  • 16
  • 28
1

For the example given:

import json

with open('inpt.txt') as json_file:
    data = json.load(json_file)

data['derivationValue'] = data['derivationValue']['OOP3']

Gives the output:

{'derivationName': 'other_lob_subcd', 'derivationValue': 'TENANT'}

In general, you can look at the solutions here.

CDJB
  • 14,043
  • 5
  • 29
  • 55
1

You can do something like this:

val = {        
   "derivationName": "other_lob_subcd",
   "derivationValue": {
      "OOP3": "TENANT"
   }
 }

val["derivationValue"] = val["derivationValue"]["OOP3"]
print(val)

This will be the output:

val = {        
   "derivationName": "other_lob_subcd",
   "derivationValue": "TENANT"
 }
Diana
  • 140
  • 1
  • 13