Skip to content
Advertisement

Cannot load a JSON file I just created (json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0))

I’m trying to work with json files, but I’m unable to load the file I just saved.

time_vals = { "seconds": time_spent, "day": amnt}
json_o = json.dumps(time_vals, indent = 4)

with open(os.path.join(os.getcwd(), fname + ".json",), 'a+') as f:
     loaded = json.loads(f.read()) <- error

     f.write(json_o)

I’m not sure what I’m doing wrong. I tried json.loads(f.read().decode('UTF-8')) and json.load(f) and they both give me errors as well.

Edit: The purpose of this code is to store time spent on something as a json, and if the time exceeds a certain amount add something else (that’s why I’m trying to load the file, to attempt to get the int values stored)

Traceback when using json.load(f):

Traceback (most recent call last):
  File "C:UsersjulktPycharmProjectspythonProjectvenvlibsite-packagesflaskapp.py", line 2070, in wsgi_app
    response = self.full_dispatch_request()
  File "C:UsersjulktPycharmProjectspythonProjectvenvlibsite-packagesflaskapp.py", line 1515, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:UsersjulktPycharmProjectspythonProjectvenvlibsite-packagesflaskapp.py", line 1513, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:UsersjulktPycharmProjectspythonProjectvenvlibsite-packagesflaskapp.py", line 1499, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "C:/Users/julkt/Documents/Python_projectaaaaaaaaaaaaas/GUI project/guiproject.py", line 346, in send_url
    loaded = json.load(f)
  File "C:UsersjulktAppDataLocalProgramsPythonPython38libjson__init__.py", line 293, in load
    return loads(fp.read(),
  File "C:UsersjulktAppDataLocalProgramsPythonPython38libjson__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "C:UsersjulktAppDataLocalProgramsPythonPython38libjsondecoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:UsersjulktAppDataLocalProgramsPythonPython38libjsondecoder.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)
192.168.1.162 - - [16/Sep/2021 18:01:25] "POST /send_url HTTP/1.1" 500 -
 

Advertisement

Answer

When you open a file “a+” (append plus read), the file pointer is set at the end of file, ready for the next write to append data. when you read, its already at EOF so you get the empty string "". Its the same as if you had witten

json.loads("")

Its hard to manage a file for writing and reading, especially with python where an intermediate encoder/decoder for bytes to str translation may be caching data. There are other details to consider such as flushing data to make sure its really available for a read.

Better to segment your code to reading bits and writing bits, and close the file in between. To get the same sequence you’ve shown, you could

import json

time_vals = { "seconds": 20, "day": 44}

# load records
try:
    with open("test.json") as f:
        records = [json.loads(line) for line in f]
    print("records", records)
except OSError:
    print("no records")

# append new record
with open("test.json", "a") as f:
    print(json.dumps(time_vals), file=f) # print record with newline

Running multiple times I get

td:~/tmp/e$ python3 test.py
records [{'seconds': 20, 'day': 44}]
td:~/tmp/e$ python3 test.py
records [{'seconds': 20, 'day': 44}, {'seconds': 20, 'day': 44}]
td:~/tmp/e$ python3 test.py
records [{'seconds': 20, 'day': 44}, {'seconds': 20, 'day': 44}, {'seconds': 20, 'day': 44}]
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement