我有一個名為“students.json”的 JSON 檔案,如下所示:-
{
"students": {
"1":{
"name": "Ricky",
"marks": {
"science": "90",
"english": "50"
}
},
"2":{
"name": "Brad",
"marks": {
"science": "80",
"english": "75"
}
}
}
}
我想將 Brad 的英文標記更新為 85。我所擁有的只是 JSON 檔案、標記路徑串列和更新的標記。
updated_marks = "85"
path_to_marks = ["students", "2", "marks", "english"]
我想做這樣的事情,
import json
updated_marks = "85"
path_to_marks = ["students", "2", "marks", "english"]
with open('students.json', 'r ') as f:
json_data = json.load(f)
value = json_data
#TODO: code to update marks
f.seek(0)
f.write(json.dumps(json_data))
f.truncate()
uj5u.com熱心網友回復:
由于您習慣于json.load通過默認轉換表將檔案加載回 Python 物件,因此您應該獲得一個字典。
因此,在您的情況下,您應該能夠像在 dict 中一樣正常編輯資料:
json_data["students"]["2"]["marks"]["english"] = updated_marks
編輯:
由于您想根據 path_to_english_marks 串列進行呼叫,因此您可以從jjp執行此處提到的類似操作。
from functools import reduce
from operator import getitem
def set_nested_item(dataDict, mapList, val):
"""Set item in nested dictionary"""
reduce(getitem, mapList[:-1], dataDict)[mapList[-1]] = val
return dataDict
key_lst = ["key1", "key2", "key3"]
value = "my_value"
d = {"key1": {"key2": {"key3": "some_value"}}}
d = set_nested_item(d, key_lst, value)
print(d)
# {'key1': {'key2': {'key3': 'my_value'}}}
uj5u.com熱心網友回復:
def update(json, path, new_value):
obj_ptr = json
for key in path:
if key == path[-1]:
obj_ptr[key] = new_value
obj_ptr = obj_ptr[key]
從您的代碼中呼叫它,如下所示:
update(json_data, path_to_marks, updated_marks)
uj5u.com熱心網友回復:
直接保存
data['students']['2']['marks']['english'] = marks
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/386387.html
下一篇:如何制作輸入字典
