Editing a dict. within a json file

Viewed 50

I need to edit a object within a dict that is located inside a json file. but whenever I attempt to do it, it would delete the entire json file and only add the thing I've edited.

Here's my function.

async def Con_Manage(keys):
    with open('keys.json') as config_file:
        config = json.load(config_file)[keys]
    try:
        Current_Con = config["curCons"] + 1
        with open('keys.json', 'w') as config_file:
            json.dump(Current_Con, config_file)
        
        return True
    except:
        return False

heres my json file before i run it

{
    "key1": {
        "time": 1500,
        "maxCons": 15,
        "curCons": 2,
        "coolDown": 2
    }
}

and here's what it looks like after its ran

3

is there any way that i can run this and not delete all my progress?

2 Answers

config["curCons"] gets you just the value which you then increment it and assign to Current_Con. Instead you need to increment and set the value to +1. From there you would want to save the entire json object that you just read in and not just the value that was updated.

async def Con_Manage(keys):
    with open('keys.json') as config_file:
        config = json.load(config_file)
    config[keys]["curCons"] += 1 # mutates the value in place 
    with open('keys.json', 'w') as keys:
        json.dump(config, keys) # saves the entire dict not just the value

You need to be writing the entire config file

you can do something like this...

with open('keys.json') as config_file:
    config = json.load(config_file)

for key in keys:
    try:
        config[key]["curCons"] += 1
    except KeyError:
        pass

with open('keys.json', 'w') as config_file:
    json.dump(config, config_file)
Related