![](/img/trans.png)
[英]How to add datafield (key-value) in json with language detection for single data field
[英]How to add a key-value to JSON data retrieved from a file?
我是 Python 新手,正在處理 JSON 數據。 我想從文件中檢索 JSON 數據,並將 JSON 鍵值“動態”添加到該數據中。
也就是說,我的json_file
包含 JSON 數據,如下所示:
{"key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}
我想將"ADDED_KEY": "ADDED_VALUE"
鍵值部分添加到上述數據中,以便在我的腳本中使用以下 JSON:
{"ADDED_KEY": "ADDED_VALUE", "key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}
我正在嘗試編寫如下內容以完成上述操作:
import json
json_data = open(json_file)
json_decoded = json.load(json_data)
# What I have to make here?!
json_data.close()
你的json_decoded
對象是一個 Python 字典; 你可以簡單地添加你的密鑰,然后重新編碼和重寫文件:
import json
with open(json_file) as json_file:
json_decoded = json.load(json_file)
json_decoded['ADDED_KEY'] = 'ADDED_VALUE'
with open(json_file, 'w') as json_file:
json.dump(json_decoded, json_file)
我在這里使用打開的文件對象作為上下文管理器(使用with
語句),因此 Python 會在完成后自動關閉文件。
從 json.loads() 返回的 Json 行為就像原生 python 列表/字典:
import json
with open("your_json_file.txt", 'r') as f:
data = json.loads(f.read()) #data becomes a dictionary
#do things with data here
data['ADDED_KEY'] = 'ADDED_VALUE'
#and then just write the data back on the file
with open("your_json_file.txt", 'w') as f:
f.write(json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')))
#I added some options for pretty printing, play around with them!
有關更多信息,請查看官方文檔
你可以做
json_decoded['ADDED_KEY'] = 'ADDED_VALUE'
或者
json_decoded.update({"ADDED_KEY":"ADDED_VALUE"})
如果您想添加多個鍵/值對,這很有效。
當然,您可能想先檢查 ADDED_KEY 是否存在 - 取決於您的需要。
而且我假設您可能希望將該數據保存回文件
json.dump(json_decoded, open(json_file,'w'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.