Change key name in json python

Hi,

Need help please. I want to change the all the key names under the key ‘source’ under all occurrences of the key ‘identifiers’ 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)

{
   "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
      },

Please put your code between triple backticks to show correctly. Here I will try to do this for you. Is this your code?

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)
I fixed indentation of the code (syntax error). Click to see.

These lines had wrong indentation (extra space):

 payrolldata = str(oldvalue).replace('name', 'newname').replace('value', 'newvalue2')
 for d in payrolldata:

You did not say what exactly is “not correct”. You should provide details, like error messages, expected result and the result obtained…

The JSON code you show is invalid. It contains a list outside of square brackets [], unclosed brackets…

In a next post I will comment your Python code. It would be much better to provide a valid JSON example.

payrolldata = str(oldvalue).replace('name', 'newname').replace('value', 'newvalue2')

Here you convert the data structure to a single string (text). By calling str() you create a new string object. You need to traverse the structure (by iterating the lists and dictionaries) instead of making a single string from it.

Start with a simple experimental code instead of the complex JSON. Create a dictionary and try to iterate it and replace its keys and values as you need.


for d in payrolldata:
    d['newName':] = d.pop["'name':"]

I see a good idea in the code. I think you wanted to replace dictionary keys with new ones while keeping the values. Hints:

  • d will iterate over individual characters of the payrolldata string. I think this is not what you want.
  • d['newName':]d will need to be a dictionary. Putting the colon there is invalid for dictionaries.
  • d.pop["'name':"]
    • pop is a method. It is not indexable, you probably want to call it. For that use round brackets. Square brackets are used for accessing dictionary or list items.
    • "'name':" for a key named by a text string containing name use just "name" or 'name'.

With your current level of knowledge this kind of task is too complex for you. Go through basic tutorials. Learn about how to work with lists and dictionaries. Try to build a simpler program for a similar task first. Then start programming this task.

Build the program gradually. Continue with next parts when the current parts are working as you intended and when you understand how they work. Be prepared to create parts of the code just to show you the inner working state of the program — diagnostic prints within loops etc.