0

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'

1
  • There is no way you can change the key. Either you will need to add new key value and remove the old or create a new dictionary with a dictionary-comprehension. Commented Apr 14, 2020 at 13:42

3 Answers 3

1

Something like this would work. We read the json into an object. iterate over the list of elements, and change the key from 'marka' to 'entity' by popping it from the dictionary and assigning it to entity key

import json
string = '[{"marka": "تويوتا" , "tag" : "MANF"}, {"marka": "شيفروليه" , "tag" : "MANF"}, {"marka": "نيسان" , "tag" : "MANF"}]'
jsonObj = json.loads(string)
for elem in jsonObj:
    elem['entity'] = elem.pop('marka')
print(jsonObj)
Sign up to request clarification or add additional context in comments.

Comments

1

You could create a mapping to your dictionary keys:

map_this = {'marka': 'entity'}

And now map the old keys to the new keys using a dictionary comprehension:

{map_this.get(k, k): v for k, v in old_dict.items()}

The syntax map_this.get(k, k) returns map_this[k] if it exists and otherwise returns k itself.


Technically, this creates a new dictionary instead of adapting your old one.

Comments

0

I think you may need a loop:

for json_elem in json_obj:
    json_elem["entity"] = json_elem.pop("marka")

pop will remove the element.

Output:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.