主檔案
import json
def test(key, value):
with open("test.json", "r", encoding="utf-8") as f:
x = json.load(f)
num = 1
try:
if f"q{num}" in x["keys"]: # Checking if index 1 is exist
for _ in range(num):
num = 1
except:
pass
x["keys"] = {}
x["keys"][f"{num}"] = {"key": key, "value": value} # Dict for json file
with open("test.json", "w", encoding="utf-8") as f:
json.dump(x, f, indent=4, ensure_ascii=False) # Write the json file
test("test", "testvalue")
test("test2", "testvalue2")
測驗.json
{
"keys": {
"1": {
"key": "test2",
"value": "testvalue2"
}
}
}
如何在不替換第二個問題的情況下保留第一個問題?我想讓它像這樣(如果可能的話):
{
"keys": {
"1": {
"key": "test",
"value": "testvalue"
},
"2": {
"key": "test2",
"value": "testvalue2"
}
}
}
我不確定是否真的可以做到這一點。如果無法做到這一點,請告訴我!
uj5u.com熱心網友回復:
你可以試試這樣的。它檢查您是否可以實際將檔案加載為 json (因為這將因空檔案而失敗),然后在 dict 中找到最大鍵值keys并添加一個帶有遞增鍵的新條目。
import json
def test(key, value):
with open("test.json", "r", encoding="utf-8") as f:
try:
x = json.load(f)
next_key = max(map(int, x['keys'].keys())) 1
except:
# empty file
x = { 'keys' : {} }
next_key = 1
# add the new value
x['keys'].update({ next_key : { 'key' : key, 'value' : value } })
# write the new data
with open("test.json", "w", encoding="utf-8") as f:
json.dump(x, f, indent=4, ensure_ascii=False)
運行后的內容test.json:
test("test", "testvalue")
test("test2", "testvalue2")
將會:
{
"keys": {
"1": {
"key": "test",
"value": "testvalue"
},
"2": {
"key": "test2",
"value": "testvalue2"
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/470160.html
標籤:Python json python-3.x
