0

I am trying to do something like this which uses reading , appending and writing at the same time.

with open("data.json", mode="a+") as file:
            # 1.Reading old data
            data = json.load(file)  
            # 2. Updating old data with new data
            data.update(new_dict)
            # 3.Writing into json file
            json.dump(data,file,indent=4)

But it shows json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

heysujal
  • 118
  • 7
  • 2
    You are appending a JSON string at the end of another, making the on-disk file invalid. You should read from the file in `r` mode, then re-open it in `w` mode to overwrite it. – Selcuk May 31 '21 at 05:03
  • 1
    I assume the error is at the time of `json.load`. Check the content of `data.json`. You seem to be appending JSON to the file, instead of replacing it, resulting in two JSON being in the file one after another after the code runs once, which would mess up the second invocation. Use `file.seek(0)` to return to the start before writing. – Amadan May 31 '21 at 05:04
  • Yes I want to append in { "google": { "email": "sujalgupta@gmail.com", "password": "8QU7w51VE$!dbCU" } } with file.seek(0) it is giving same error. – heysujal May 31 '21 at 05:09
  • https://stackoverflow.com/questions/67717534/pythonic-way-to-update-multiple-values-stored-within-a-json-dict/67717833#67717833 – leaf_yakitori May 31 '21 at 06:24

1 Answers1

0

First you need to open the file in mode="r+". Update the old data with new, then seek(0) to the beginning of the file, write your updated json data, and then truncate the rest:

with open("data.json", mode="r+") as file:
    file.seek(0, 2)
    if file.tell():
        file.seek(0)
        data = json.load(file)  
        data.update(new_dict)
    else:
        data = new_dict
    file.seek(0)
    json.dump(data, file, indent=4)
    file.truncate()

Reason it doesn't work with a+ mode is that it will always write at the end of the file, irrespective of seek(0). So your updated json data just gets appended to the older one like a normal text data, but since its not a valid json syntax, it causes JSON Decode error.

Check here for more detailed info on how the different open modes work.

Ank
  • 1,704
  • 9
  • 14
  • This doesn't work . Check Line 55 https://replit.com/@heysujal/Password-manager#main.py – heysujal Jun 01 '21 at 08:22
  • @Sujal Ok I checked your code and `data.json` file. The issue is that initially your `data.json` is an empty file. So `json` cannot load it since it needs a valid entry. I have modified the code to handle this. Try the edited code now above. – Ank Jun 01 '21 at 09:38
  • I will let you know when I try this. – heysujal Jun 02 '21 at 14:55