我目前正在嘗試編輯一個 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}} ]
我想將所有“名稱”鍵更改為“名稱”,并將所有“Hight”鍵更改為“HIGHT (ft)”。
我正在使用 Python,這是我正在嘗試編輯的 100 個字典的資料集,因此一次瀏覽一個效率不高。
uj5u.com熱心網友回復:
我假設模式實際上是格式良好的(引號中的“屬性”,使用雙引號而不是單引號,串列中物件之間的逗號)。
您可以執行以下操作來重命名欄位:
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))
uj5u.com熱心網友回復:
如果您在大寫下有多個鍵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))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/400153.html
上一篇:從字典或元組中找出最大值
