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'

2
  • 1
    I think the problem is in your input data. If you print(d) before assignment what is the last value before error? Commented Apr 14, 2020 at 16:15
  • Does this answer your question? How to update json key name in python. Your identical question from 2 hours ago for which you received 3 answers. Commented Apr 14, 2020 at 16:20

4 Answers 4

0

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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])

3 Comments

I tried your code and it prints the data after editing the key name to "entity" but the data in the file is the same I mean the key name didn't change to "entity", how?
This code is just to find the jsons without marka key. You should run it after this line: data = json.load(jsonFile). If there are jsons without the key, you have to decide - fix them or decide how to process them.
the problem is solved, actually, the file was opened multiple time and it couldn't make the updates. thanks.
0

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)

Comments

0

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

Comments

Your Answer

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