0

In the above JSON file, I have header names like 901, 9x1 and 9x2.

I want to change the header names like this:

  • 9x1 to 911
  • 9x2 to 912

I have tried following approach using python

tot = [911,912]
data = "above mentioned json file"
    for j in data:
        for i in tot:
           if j == '9x1':
             data[j][0] = i

The JSON file:

{
  "901": [
    {
      "section": "Revision",
      "section": "Appendix A",
      "section": "Region Code",
      "Table": "Region",
      "Bundle": "1.0.0.9",
      "Software": "1.0.0.2",
      "iOS Simulator": "1.1.1.1",
      "Configuration": "1.0.0.1"
    }
  ],
  "9x1": [
    {
      "section": "Revision",
      "section": "Appendix A",
      "section": "Region Code ",
      "Table": "Region",
      "Bundle": "1.0.0.9",
      "Software": "1.0.0.2",
      "iOS Simulator": "1.1.1.1",
      "Configuration": "1.0.0.1"
    }
  ],
  "9x2": [
    {
      "section": "Revision",
      "section": "Appendix A",
      "section": "Region Code",
      "Table": "Region",
      "Bundle": "1.0.0.9",
      "Software": "1.0.0.2",
      "iOS Simulator": "1.1.1.1",
      "Configuration": "1.0.0.1"
    }
  ]
}
UShukla
  • 21
  • 6
  • Does this answer your question? [Change the name of a key in dictionary](https://stackoverflow.com/questions/4406501/change-the-name-of-a-key-in-dictionary) – Benoît Zu Jun 23 '22 at 11:52
  • Perhaps not as i am keeping the values to change in a list and looking to change in json file – UShukla Jun 23 '22 at 12:03

2 Answers2

1

Following should work for you.

tot = [911,912]
data = "above mentioned json file"
for i in tot:
    if '9x1' in data:
        data[i] = data.pop('9x1')

Suggestion:

tot = {'9x1': 911, '9x2': 912}
data = "above mentioned json file"
for old_value, new_value in tot.items():
    if old_value in data:
        data[new_value] = data.pop(old_value)
Chamath
  • 2,016
  • 2
  • 21
  • 30
  • thanks it worked when i have to change only for '9x1' how should i handle the case where i need to change multiple value i.e '9x2' with '912' , '9x3' with '913' – UShukla Jun 23 '22 at 12:12
  • @UShukla Updated answer with the suggestion. I have updated `tot` to be a `dict` which will include all the old_values and new_values combinations. – Chamath Jun 23 '22 at 12:20
0

Create a mapping dictionary and iterate over data, lookup the old key in renameMapping, if found the new key is used elsewise the old one:

renameMapping = {"9x1": "911", "9x2": "912"}
data = {renameMapping.get(oldKey, oldKey): v for oldKey, v in data.items()}
print(data.keys())

Out:

dict_keys(['901', '911', '912'])
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47