Home > OS >  loading a datetime from a json
loading a datetime from a json

Time:10-22

I am storing a datetime object to now when to re-stock, however when trying to load the datetime I get an error like: JSONDecodeError: Expecting value: line 1 column 1 (char 0) I hae no clue on what any of this means since I did not write the JSON lib requesting some help over and out.

Here is my current code

datetime.datetime.strptime(json.loads(File.read())["lastStocked"], "%Y-%m-%d %H:%M:%S.%f")

here is the json file

{
    "Reserve": 1000,
    "lastStocked": "2022-10-21 21:28:36.408608",
    "nextStocked": "2022-10-21 21:28:36.408672"
}

CodePudding user response:

File.read() is returning an empty string. That's why the error is indicating the first character of the first line.

You didn't post all of the relevant code, but I would guess you're calling File.read() twice. After the first read the file read pointer is at the end of the file so the second read returns nothing. Solutions include:

  • Copying the contents of the file to a variable and using that (only call File.read() once)
  • Call File.seek(0) before calling File.read() the second time
  • Close and re-open the file before calling File.read() the second time

Or the bug is somewhere else.

CodePudding user response:

Guessing at the missing code, I could reproduce the problem if the JSON was saved as UTF-8 w/ BOM encoding, which adds bytes EF BB BF (the UTF-8 encoding of the U FEFF byte order mark character) to the beginning of the file as a UTF-8 signature. The JSON encoder doesn't like that:

import json
import datetime

with open('test.json') as File:
    # simple way to debug...actually look at the data
    data = File.read()
    print(ascii(data))
    print(datetime.datetime.strptime(json.loads(data)["lastStocked"], "%Y-%m-%d %H:%M:%S.%f"))

Output below. Note the \xef\xbb\xbf printed at the start of the file:

'\xef\xbb\xbf{\n    "Reserve": 1000,\n    "lastStocked": "2022-10-21 21:28:36.408608",\n    "nextStocked": "2022-10-21 21:28:36.408672"\n}'
Traceback (most recent call last):
    ...
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

The following code will work, as utf-8-sig encoding will remove the BOM if present.

import json
import datetime

with open('test.json', encoding='utf-8-sig') as File:
    print(datetime.datetime.strptime(json.loads(File.read())["lastStocked"], "%Y-%m-%d %H:%M:%S.%f"))

or more simply with json.load instead:

import json
import datetime

with open('test.json', encoding='utf-8-sig') as File:
    print(datetime.datetime.strptime(json.load(File)["lastStocked"], "%Y-%m-%d %H:%M:%S.%f"))

Output:

2022-10-21 21:28:36.408608
  • Related