In the above JSON file, I have header names like 901
, 9x1
and 9x2
.
I want to change the header names like this:
9x1
to911
9x2
to912
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"
}
]
}
CodePudding user response:
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)
CodePudding user response:
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'])