Skip to content
Advertisement

How do I read and then update a json file?

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:ProjectsProgramsCalculatorstackQuestion.py", line 22, in <module>
    readObj = json.load(savefile)
  File "C:UsershpAppDataLocalProgramsPythonPython39libjson__init__.py", line 293, in load
    return loads(fp.read(),
  File "C:UsershpAppDataLocalProgramsPythonPython39libjson__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:UsershpAppDataLocalProgramsPythonPython39libjsondecoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:UsershpAppDataLocalProgramsPythonPython39libjsondecoder.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’

Advertisement

Answer

You cannot read and write the json file with the same with clause. Kindly use this code to get rid of that error that are the read and write buffers that not allowing you to write while reading at the same time

import pathlib
import json
import os

obj = {
        "a": "1",
        "b": "2",
        "c": "3"
    }
obj2 = {
        "d": "4",
        "e": "5",
        "f": "6"
    }


jsonFile = "jsonFile1.json"

print(obj)
if os.path.exists(jsonFile) == False:
    print("1123")
    with open(jsonFile, "w") as savefile:
        json.dump(obj, savefile)
else:
    with open(jsonFile, "r") as json_file:
        readObj = json.load(json_file)
        readObj.update(obj2)
        print(readObj)
        
        
    with open(jsonFile, "w") as json_file:
        json.dump(readObj, json_file)
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement