如何在不替换新密钥的情况下保留 JSON 中的第一个密钥?
How can I keep the first key in the JSON without replacing the new one?
Main.py
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")
test.json
{
"keys": {
"1": {
"key": "test2",
"value": "testvalue2"
}
}
}
如何保留第一个问题而不替换第二个问题?我想这样做(如果可能的话):
{
"keys": {
"1": {
"key": "test",
"value": "testvalue"
},
"2": {
"key": "test2",
"value": "testvalue2"
}
}
}
我不确定是否真的可以做到这一点。如果无法做到这一点,请告诉我!
你可以尝试这样的事情。它检查您是否真的可以将文件加载为 json(因为加载空文件会失败),然后在 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"
}
}
}
Main.py
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")
test.json
{
"keys": {
"1": {
"key": "test2",
"value": "testvalue2"
}
}
}
如何保留第一个问题而不替换第二个问题?我想这样做(如果可能的话):
{
"keys": {
"1": {
"key": "test",
"value": "testvalue"
},
"2": {
"key": "test2",
"value": "testvalue2"
}
}
}
我不确定是否真的可以做到这一点。如果无法做到这一点,请告诉我!
你可以尝试这样的事情。它检查您是否真的可以将文件加载为 json(因为加载空文件会失败),然后在 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"
}
}
}