I’m currently working on another school project where I have to write to a .json file. As it depends on if the file is empty or not, I have a simple if clause in my code which handles this:
json_start = {"messages": []}
with open(self._db, 'r') as json_file:
first_char = json_file.read(1)
if not first_char:
json_content = json_start
last_id = 0
else:
json_content = json.load(json_file)
message_list = json_content.get("messages")
last_id = message_list[-1].get("id")
As you can see, I read the first char of json_file
to decide if the file is empty or not, and when it’s not, I load the contents of the file into json_content
with json.load(json_file)
. When the file is empty, everything works accordingly.
However, if my file has content in it, like this:
{
"messages": [
{
"id": 1,
"header": "Subj 1",
"body": "body 1"
}
]
}
For some odd reason I get an JSONDecodeError: Extra data
. I’ve checked if there aren’t any whitespaces in the file where they shouldn’t be, and there’s nothing to be found.
Just why do I get this error?
2
Answers
After you call
json_file.read(1)
,json.load()
will start reading from the second character of the file, which will be invalid. You should rewind back to the beginning of the file.Personally, I would just write
to the
_db
file when you create the instance of the class. Then you don’t need to check whether the file is empty when you read it and you can simplify your code to: