How to change json key name with python

Viewed 50

Need some help please.

I have a similar json file:

{
   "timestamp": "2022-09-20T08:16:00.000Z",
   "metadata": {   
   "orgID": "6780",
   "projectId": 0988,
  }
 },
 {
  "data":  
   "workers": [      
    {
     "identifiers": { 
      "FullName": null,
      "NINumber": null,
      "CompID": null
     },
     "lastName": null,
     "costCenter": null
    },
    {
     "codes": [  
       {
       "source": {
        "name": "net_salary",
        "value": 11500
       },
       "name": "net_salary",
       "code": "rt_sa",
       "value": 11500
      },
 {
     "identifiers": {
      "FullName": null,
      "NINumber": null,
      Comp ID": null
     },
     "lastName": null,
     "costCenter": null
    },
    {
     "codes": [
      {
       "source": {
        "name": "hiredate",
        "value": 3.333
       },
       "name": "hiredate",
       "code": "h_code",
       "value": 3.333
      },

I want to change the key names under source from name->fieldname and value to fieldvalue. However, I don't want to change the keys where there are the keys: name, code, value.

I tried this but it is not correct:

with open(r'C:\Users\Administrator\Documents\test\PJSON.json') as f:
    payrolldata = json.load(f)
    source = payrolldata[1]['data']['workers'][1]['codes'][1]['source']
    print(source)
    oldvalue = source.keys()
    print(str(oldvalue).replace('name', 'newname').replace('value', 'value2'))
 payrolldata = str(oldvalue).replace('name', 'newname').replace('value', 'newvalue2')
 for d in payrolldata:
     d['newName':] = d.pop["'name':"]


with open(r'C:\Users\Administrator\Documents\test\PJSON.json', "w") as f:
  json.dump(payrolldata, f, indent=4)
1 Answers

I suggest you don't convert your dict into string and use something like this on you dict read from json file (with json.load)

def deep_replace_key(d, old_key:str, new_key:str):
    if isinstance(d, dict):
        if old_key in d:
            d[new_key] = d.pop(old_key)
        for k, v in d.items():
            deep_replace_key(v, old_key, new_key)
    elif isinstance(d, list):
        for item in d:
            deep_replace_key(item, old_key, new_key)
    return d

and apply this function to you dict multiple times

if you want in one go then this

def deep_replace_key(d, old_new_key_pairs:dict):
    if isinstance(d, dict):
        for old_key, new_key in old_new_key_pairs.items():
            if old_key in d:
                d[new_key] = d.pop(old_key)
        for k, v in d.items():
            deep_replace_key(v, old_new_key_pairs)
    elif isinstance(d, list):
        for item in d:
            deep_replace_key(item, old_new_key_pairs)
    return d
Related