简体   繁体   English

使用 python 重命名 json 文件中的密钥名称

[英]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:我想更新我的 json 文件中的键名,文件中的对象如下所示:

[{"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:我想将键名“marka”更改为“entity”,所以它会是这样的:

[{"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'文件“marka.py”,第 8 行,在 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.keys()就像这样 ->

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

to see if the key is actually marka and not something else.看看钥匙是否真的是marka而不是别的东西。

The code works well, the problem is in your input data.该代码运行良好,问题出在您的输入数据中。 One of the jsons in your file doesn't have marka key.您文件中的 json 之一没有marka键。

In order to find the invalid jsons, you can run:为了找到无效的 json,您可以运行:

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这将帮助您更新值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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