Home > Software design >  Update same object in a JSON file without creating a new object inside it
Update same object in a JSON file without creating a new object inside it

Time:08-12

I have an empty json file which I'm trying to update based on user input. Initially there is no content inside the json file.

I've created an endpoint to take input from the user in following format via Flask app :

{
    "register_address_lower":40201,
    "register_address_upper":40202,
    "unit":"gal/min"
}

So after getting the input for first time the content of the json file looks like this :

{"40201": "gal/min", "40202": "gal/min"}

Now after getting new user inputs I just want to update the same object in the json file without creating a new object in it. Suppose the new input is :

{
    "register_address_lower":40801,
    "register_address_upper":40803,
    "unit":"gal/min"
}

The content inside my json file now should be : -

{"40201": "gal/min", "40202": "gal/min", "40801": "gal/min", "40802": "gal/min", "40803": "gal/min"}

This is the block of code I'm using :

@app.route("/config",methods=["Post"])
def update_json():
    response = request.json
    with open("config.json", 'r ') as file:
        json_file = json.load(file)
        for res_address in range(response['register_address_lower'],response['register_address_upper'] 1):
            new_reg = {str(res_address):response['unit']}
            json_file.update(new_reg)
            #json_file[res_address]=response['unit']
        
        json.dump(json_file, file)

And the result I'm getting by passing the above given examples is : -

{"40201": "gal/min", "40202": "gal/min"}{"40201": "gal/min",
 "40202": "gal/min", "40801": "gal/min", "40802": "gal/min", "40803": "gal/min"}

CodePudding user response:

The file you are opening in is in 'r ' mode, so you are reading from it, but when you dump to it you start after the contents that are already there. The 2nd object in the file is the expected output as I understand it. You need to overwrite the file outside the with you currently have.

The below is an untested rewrite:

@app.route("/config",methods=["Post"])
def update_json():
    response = request.json
    with open("config.json", 'r ') as file:
        json_file = json.load(file)
    for res_address in range(response['register_address_lower'],response['register_address_upper'] 1):
            new_reg = {str(res_address):response['unit']}
            json_file.update(new_reg)
            #json_file[res_address]=response['unit']
    
     with open("config.json", 'w') as file: 
        json.dump(json_file, file)
  • Related