如何在一个JSON文件中更改多个键,该文件具有多个字典,这些字典使用Python合并了相同的键但不同的值



我目前正在尝试编辑一个JSON文件,该文件包含多个列出的字典,这些字典包含相同的键但不同的值。我想更改文件中每个字典中的特定键(相同的键(。我该怎么做?

例如:

"JSON_ FILE";[

{"type" : "person", 'attributes" : { "Name" : "Jack, "Age" : 24, "Hight" : 6.2}}
{"type" : "person", "attributes" : { "Name" : "Brent", "Age" : 15, "Hight" : 5.6}}
{"type" : "person", "attributes" : { "Name" : "Matt", "Age" : 30, "Hight" : 4.9}}  ] 

我想将所有的"Name"键都标记为"名称";以及所有"Hight"键标记为"HIGH(ft("。

我使用的是Python,这是一个由100个字典组成的数据集,我正在尝试编辑,所以一次编辑一个字典是不高效的。

我假设模式实际上是格式良好的(引号中的"attributes",使用双引号而不是单引号,列表中对象之间的逗号(。

您可以执行以下操作来重命名字段:

import json
data = json.load(open('your_file_name.json', 'r'))
for data_entry in data:
# Add new 'NAME' field, then delete old 'Name' field.
data_entry['attributes']['NAME'] = data_entry['attributes']['Name']
del data_entry['attributes']['Name']
# Add new 'HIGHT' (sic) field, then delete old 'Hight' field.
data_entry['attributes']['HIGHT'] = data_entry['attributes']['Hight']
del data_entry['attributes']['Hight']
with open('your_file_name.json', 'w') as output_file:
output_file.write(json.dumps(data))

如果您在attributes到大写下有多个键,您可以执行以下操作:

import json
file_path = "path/to/file"
fields_to_upper = ["Name", "Hight", "Age"]
with open(file_path, "r") as f:
data = json.load(f)
for row in data:
for field in fields_to_upper:
row["attributes"][field.upper()] = row["attributes"].pop(field)
with open(file_path, "w") as f:
f.write(json.dumps(data))

如果您想将attributes下的所有密钥大写,请尝试:

with open(file_path, "r") as f:
data = json.load(f)
for row in data:
for key in row["attributes"].keys():
row["attributes"][key.upper()] = row["attributes"].pop(key)
with open(file_path, "w") as f:
f.write(json.dumps(data))

最新更新