在我的 python 程序中使用 json 文件。我需要從函數中修改 json 文件以添加一個空的“占位符”元素。我只想為 convID 對象中包含的鍵添加一個空元素。json 庫是否允許以更簡單的方式將元素附加到 json 文件?示例.json:{"1005672": "Testing needles note", "1005339": "Reply", "988608": "Received the message"}我希望發生這種情況(convID表示存儲在 convID 對象中的鍵):{"1005672": "Testing needles note", "1005339": "Reply", "988608": "Received the message", "*convID*": "none"}我猜我必須將 json 加載到字典對象中,進行修改并將其寫回文件......但這對我來說很困難,因為我還在學習。這是我的搖擺:def updateJSON(): jsonCache={} # type: Dict with open(example.json) as j: jsonCache=json.load(j) *some code to make append element modification with open('example.json', 'w') as k: k.write(jsonCache)
2 回答

RISEBY
TA貢獻1856條經驗 獲得超5個贊
請使用 PEP8 風格指南。
以下代碼段將起作用
導入json
def update_json(): with open('example.json', 'r') as file: json_cache = json.load(file) json_cache['convID'] = None with open('example.json', 'w') as file: json.dump(json_cache, file)

白板的微信
TA貢獻1883條經驗 獲得超3個贊
要將鍵添加到 dict,只需將其命名:
your_dict['convID'] = 'convID_value'
因此,您的代碼將類似于:
import json
# read a file, or get a string
your_json = '{"1005672": "Testing needles note", "1005339": "Reply", "988608": "Received the message"}'
your_dict = json.loads(your_json)
your_dict['convID'] = 'convID_value'
因此,將它與您的代碼一起使用,它將是:
def update_json():
json_cache = {}
with open('example.json', 'r') as j:
json_cache = json.load(j)
json_cache['convID'] = 'the value you want'
with open('example.json', 'w') as k:
json.dump(json_cache, f)
添加回答
舉報
0/150
提交
取消