I need to be able to update a json
file in python. I can get it to create and write to the json
file the first time, but it keeps telling me I have an json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
.
Here's the code:
import pathlib
import json
obj = {
"a": "1",
"b": "2",
"c": "3"
}
obj2 = {
"d": "4",
"e": "5",
"f": "6"
}
jsonFile = pathlib.Path("jsonFile.json")
if jsonFile.exists() == False:
with open("jsonFile.json", "w") as savefile:
dumpJSON = json.dump(obj, savefile)
else:
with open("jsonFile.json", "w+") as savefile:
readObj = json.load(savefile)
readObj.update(obj2)
dumpJSON = json.dump(readObj, savefile)
Here's the full traceback.
Traceback (most recent call last):
File "h:\Projects\Programs\Calculator\stackQuestion.py", line 22, in <module>
readObj = json.load(savefile)
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I'm using Python 3.9.2
.
I've searched the following sites:
Read, Write, and Parse JSON using Python
Python-Difference Between json.load and json.loads
Append to JSON file using Python
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
How do I write JSON data to a file?
Python JSON AttributeError: 'str' object has no attribute 'read'