skip to Main Content

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


  1. 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.

    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_file.seek(0)
            json_content = json.load(json_file)
            message_list = json_content.get("messages")
            last_id = message_list[-1].get("id")
    
    Login or Signup to reply.
  2. Personally, I would just write

    {"messages": []}
    

    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:

    with open(self._db, 'r') as json_file:
        json_content = json.load(json_file)
        message_list = json_content.get("messages")
        last_id = message_list[-1].get("id")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search