-1

Scenario is i need to convert dictionary object as json and write to a file . New Dictionary objects would be sent on every write_to_file() method call and i have to append Json to the file .Following is the code

def write_to_file(self, dict=None):
        f = open("/Users/xyz/Desktop/file.json", "w+")
        if json.load(f)!= None:
            data = json.load(f)
            data.update(dict)
            f = open("/Users/xyz/Desktop/file.json", "w+")
            f.write(json.dumps(data))
        else:

            f = open("/Users/xyz/Desktop/file.json", "w+")
            f.write(json.dumps(dict)

Getting this error "No JSON object could be decoded" and Json is not written to the file. Can anyone help ?

1 Answers1

2

this looks overcomplex and highly buggy. Opening the file several times, in w+ mode, and reading it twice won't get you nowhere but will create an empty file that json won't be able to read.

  • I would test if the file exists, if so I'm reading it (else create an empty dict).
  • this default None argument makes no sense. You have to pass a dictionary or the update method won't work. Well, we can skip the update if the object is "falsy".
  • don't use dict as a variable name
  • in the end, overwrite the file with a new version of your data (w+ and r+ should be reserved to fixed size/binary files, not text/json/xml files)

Like this:

def write_to_file(self, new_data=None):
     # define filename to avoid copy/paste
     filename = "/Users/xyz/Desktop/file.json"

     data = {}  # in case the file doesn't exist yet
     if os.path.exists(filename):
        with open(filename) as f:
           data = json.load(f)

     # update data with new_data if non-None/empty
     if new_data:
        data.update(new_data)

     # write the updated dictionary, create file if
     # didn't exist
     with open(filename,"w") as f:
         json.dump(data,f)
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219