. Advertisement .
..3..
. Advertisement .
..4..
The “JSONDecodeError: Expecting value: line 1 column 1 (char 0)” error can happen when you test your newly written Python program with different JSON data sources. Check this tutorial out to see why it happens and what could be done about it.
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Reproduce The Error
Most of the time, you will need to use the load() and loads() functions from the json library to deserialize a string or file that contains a JSON document.
The main difference between load() and loads() is the source of this JSON data. With load(), you can import JSON from a text or binary file, while loads() only deals with strings, bytes literals, and bytearray instances.
However, they produce the same error when given an invalid JSON source.
Example 1 (data.json is an empty file):
import json
json_file = "data.json"
with open(json_file, 'r') as f:
data = json.load(f)
print(data)
Output:
File "json_decoder.py", line 7, in <module>
data = json.load(f)
File "/usr/lib/python3.10/json/__init__.py", line 293, in load
return loads(fp.read(),
File "/usr/lib/python3.10/json/__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.10/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.10/json/decoder.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)
The json.load() function raises a JSONDecodeError exception when you feed it with an empty file. In a similar manner, we can try to call the json.loads() function with an empty string. As you can see, the same error message is created.
>>> json.loads('')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.10/json/__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.10/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.10/json/decoder.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)
How To Fix The Error
Checking the JSON source and replacing it with a valid JSON file or string should help you get rid of the problem.
For instance, if you insert this content into the data.json file, the first snippet should run fine now.
{
"firstName": "Richard",
"lastName": "Winters",
"age": 43,
"hobbies": ["basketball", "skydiving", "gardening"],
"children": [
{
"firstName": "Johnson",
"age": 12
},
{
"firstName": "Edith",
"age": 4
}
]
}
Output:
{'firstName': 'Richard', 'lastName': 'Winters', 'age': 43, 'hobbies': ['basketball', 'skydiving', 'gardening'], 'children': [{'firstName': 'Johnson', 'age': 12}, {'firstName': 'Edith', 'age': 4}]}
The program has loaded the content of the text file successfully. Note: check this guide if you want to format the JSON output.
Similarly, the json.loads() function works without a problem when given a valid JSON string.
>>> data = '{"name": "Johnson", "age": 34, "occupation": "software engineer"}'
>>> json.loads(data)
{'name': 'Johnson', 'age': 34, 'occupation': 'software engineer'}
But how can we deal with an unknown data source and avoid this fatal error? You can handle the exception related to the error and prevent it from stop our program.
This program will check a JSON source and print an error message of your choice when it sees an exception. The program won’t be interrupted no matter what you have given to the json.loads function.
import json
# a valid JSON string
str1 = '{"name": "Johnson", "age": 34, "occupation": "software engineer"}'
# an invalid JSON string
str2 = ''
# validate json strings
def json_validate(str):
try:
json.loads(str)
print ("This is a valid json string.")
except ValueError as e:
print ("This is not a valid json string.")
json_validate(str1)
json_validate(str2)
Output:
This is a valid json string.
This is not a valid json string.
Conclusion
It is quite simple to deal with the “JSONDecodeError: Expecting value: line 1 column 1 (char 0)” error. Change your code so it can check for the validity of JSON sources, and this problem should go away.
Leave a comment