[Python3]Encountered an error "json.decoder.JSONDecodeError: Expecting value ~"
I encountered an error below when I load some JSON files and parse them in Python.
json.decoder.JSONDecodeError: Expecting value: line 1 column 19 (char 18)
The loaded JSON file is like below.
The error seems to be occurred in "True."
{"domain": "hoge.jp", "httpOnly": True, ...
First, I suspected the cause was "True" is not recognized as a boolean value, because it is not surrounded by double-quotes.
But it was different since other int values were parsed correctly without being surrounded by double-quotes.
In the end, a cause of the error was a specification that we cannot parse unless it is "true" instead of "True."
I was very surprised because Python uses "True."
Strangely, the JSON data obtained directly from the API could be parsed properly even with "True."
Why doesn't it work with a JSON file?
Anyway, my working code is below.
It replaces "True" to "true," and "False" to "false."
You can use it when you parse a JSON file.
with open(JSON_FILE_PATH, mode = 'r', encoding = 'utf-8') as fh: json_txt = fh.read() json_txt = str(json_txt).replace("'", '"').replace('True', 'true').replace('False', 'false') json_data = json.loads(json_txt)
As a side note, ".replace("'", '"')" is to avoid errors that occur when a value is enclosed in single quotes.
It is better to use double-quotes.
Be careful if single-quotes are included in the value, or replacing it will change the value!
この記事へのコメントはこちら