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"
}
}
}
How can I keep the first question without replacing the second one? I wanted to make it like this (If it possible):
{
"keys": {
"1": {
"key": "test",
"value": "testvalue"
},
"2": {
"key": "test2",
"value": "testvalue2"
}
}
}
I'm not sure if its really possible to make it like this. If its not possible to do this, please let me know!
CodePudding user response:
You could try something like this. It checks whether you can actually load the file as json (since that will fail with an empty file), then finds the maximum key value in the keys
dict and adds a new entry with an incremented key.
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)
Contents of test.json
after running:
test("test", "testvalue")
test("test2", "testvalue2")
will be:
{
"keys": {
"1": {
"key": "test",
"value": "testvalue"
},
"2": {
"key": "test2",
"value": "testvalue2"
}
}
}