简体   繁体   中英

Rename the key name in json file using python

I want to update a key name in my json file, the objects in the file look like:

[{"marka": "تويوتا" , "tag" : "MANF"},
{"marka": "شيفروليه" , "tag" : "MANF"},
{"marka": "نيسان" , "tag" : "MANF"}]

I want to change the key name "marka" into "entity", so it will be something like this:

[{"entity": "تويوتا" , "tag" : "MANF"},
 {"entity": "شيفروليه" , "tag" : "MANF"},
 {"entity": "نيسان" , "tag" : "MANF"}]

This is the code I've tried but it gives an error:

import json
with open("haraj_marka_arabic.json", "r") as jsonFile:
     data = json.load(jsonFile)

for d in data:
    d["entity"] = d.pop("marka")

with open("haraj_marka_arabic.json", "w") as jsonFile:
    json.dump(data, jsonFile)

The error is:

File "marka.py", line 8, in d["entity"] = d.pop("marka") KeyError: 'marka'

Your problem is with the input data.

just add a debugging logger into the for loop where you change the key name and print d.keys() before changing the key name just like this ->

for d in data:
    print(d.keys())
    d["entity"] = d.pop("marka")

to see if the key is actually marka and not something else.

The code works well, the problem is in your input data. One of the jsons in your file doesn't have marka key.

In order to find the invalid jsons, you can run:

print([d for d in data if "marka" not in d])

You could make the rename conditional:

for d in data:
    if "marka" in d : d["entity"] = d.pop("marka")

or set a default value:

for d in data:
    d["entity"] = d.pop("marka",None)

import json
with open("haraj_marka_arabic.json", "r") as jsonFile:
     data = json.load(jsonFile)

for d in data:
    d['entity'] = d['marka']
    del d['marka']

with open("haraj_marka_arabic.json", "w") as jsonFile:
    json.dump(data, jsonFile)

this will help you to update values

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM