Last updated: Apr 8, 2024
Reading timeยท8 min
The Python "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)" occurs when we try to parse something that is not valid JSON as if it were.
To solve the error, make sure the response or the file is not empty, or conditionally check for the content type before parsing.
Here is a very simple example of how the error occurs.
import json # โ๏ธ json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) result = json.loads('')
We are trying to parse an empty string as if it were valid JSON.
If you just need to handle the exception if the string is not valid JSON, use a try/except statement.
import json my_str = '' try: result = json.loads(my_str) except json.decoder.JSONDecodeError: # ๐๏ธ this runs print('The string does NOT contain valid JSON')
If an error is raised, the except
block runs.
The same can be done when reading from a file.
import json file_name = 'example.json' with open(file_name, 'r', encoding='utf-8') as f: try: my_data = json.load(f) # ๐๏ธ Parse the JSON with load() print(my_data) except BaseException as e: print('The file contains invalid JSON')
The most common causes of the error are:
text/html
) as
if it were JSON.Here is an example of a file that stores invalid JSON.
{ "id": 1, 'name': "Alice", "age": 30, "country": "Austria" }
Notice that the name
property is wrapped in single quotes.
This makes the JSON invalid and trying to read from the file causes the error.
import json file_name = 'example.json' # โ๏ธ json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 3 column 3 (char 15) with open(file_name, 'r', encoding='utf-8') as f: my_data = json.load(f) print(my_data)
To solve the error, make sure to wrap all keys and string values in your JSON in double quotes.
{ "id": 1, "name": "Alice", "age": 30, "country": "Austria" }
Now the name
key is wrapped in double quotes and we can safely read from the
file.
# โ Works as expected import json file_name = 'example.json' with open(file_name, 'r', encoding='utf-8') as f: my_data = json.load(f) # ๐๏ธ {'id': 1, 'name': 'Alice', 'age': 30, 'country': 'Austria'} print(my_data) print(my_data['name']) # ๐๏ธ Alice
encoding
keyword argument when opening the file (as shown in the code sample above).Here are some examples of invalid and valid JSON values.
// โ๏ธ Invalid JSON (forgot to quote a property) { "name": "Alice", age: 30 }
The age
property in the object is not wrapped in double quotes which makes the
JSON invalid.
// โ Valid JSON (all properties are double-quoted) { "name": "Alice", "age": 30 }
The JSON in the example is valid because all properties and string values are wrapped in double quotes.
Make sure that no properties or string values are wrapped in single quotes.
// โ๏ธ Invalid JSON (name property wrapped in single quotes) { 'name': "Alice", "age": 30 }
The name
property in the example is wrapped in single quotes which makes the
JSON invalid.
You should never use single quotes in JSON. Property names and string values must be wrapped in double quotes.
// โ Valid JSON (property names and values are double-quoted) { "name": "Alice", "age": 30 }
Having a trailing comma after the last element of an array or the last key-value pair makes your JSON invalid.
// โ๏ธ Invalid JSON (trailing comma after last property) { "name": "Alice", "age": 30, ๐๏ธ this comma makes it invalid JSON }
Notice that there is a trailing comma after the age
property.
This makes the JSON invalid because trailing commas are not allowed.
To solve the error, make sure to remove all trailing commas.
// โ Valid JSON (no trailing commas) { "name": "Alice", "age": 30 }
If you are getting the error while making an API request, make sure the response
has an application/json
content-type header before parsing it.
import requests def make_request(): response = requests.delete( 'https://reqres.in/api/users/2', timeout=10 ) print('response: ๐๏ธ', response) # response: ๐๏ธ <Response [204]> print('response.text: ๐๏ธ', response.text) # response.text: ๐๏ธ "" # response.status_code: ๐๏ธ 204 print('response.status_code: ๐๏ธ', response.status_code) print('response.headers: ๐๏ธ', response.headers) if (response.status_code != 204 and 'content-type' in response.headers and 'application/json' in response.headers['content-type']): parsed = response.json() print('โ parsed response: ๐๏ธ', parsed) else: # ๐๏ธ this runs print('โ๏ธ conditions not met') make_request()
The example uses the requests
package and makes an HTTP DELETE
request which
returns a 204 status (no content).
Trying to parse an empty response as if it were JSON raises a JSONDecodeError
,
so we have to check that:
204
(No content).content-type
key.content-type
key is application/json
.This way we can be sure that the server has sent us a valid JSON response before
trying to parse it with the reponse.json()
method (if using requests
) or
with json.loads(my_json_str)
.
If the server sent you an empty response or the response is not of type
application/json
you would get a JSONDecodeError
.
You can't try to parse a text/html
or an XML
response (or an empty response)
as if it were JSON.
The error is often caused when:
You can use the json.load()
method to deserialize a JSON file to a Python
object.
import json file_name = 'example.json' with open(file_name, 'r', encoding='utf-8') as f: my_data = json.load(f) # ๐๏ธ Parse the JSON with load() print(my_data) # ๐๏ธ {'name': 'Alice', 'age': 30}
The example assumes that there is a file called example.json
located in the
same directory.
{"name": "Alice", "age": 30}
Make sure that the file that you are reading from is not empty as that often causes the error.
try/except
statement to handle a potential errorIf your file may contain invalid JSON, use a try/except
statement to handle
the error.
Let's say we have the following JSON file.
{ "name": "Alice", 'age': 30 }
Notice that the age
property is single-quoted which makes the JSON invalid.
Here's how we can use a try/except
statement to handle the error.
import json file_name = 'example.json' with open(file_name, 'r', encoding='utf-8') as f: try: my_data = json.load(f) # ๐๏ธ Parse the JSON with load() print(my_data) except BaseException as e: print('The file contains invalid JSON')
We try to parse the JSON data from the file, but the file contains invalid JSON, so an exception is raised and is then handled in the except block.
json.loads()
Another common cause of the error is passing the file path to the json.loads()
method when trying to read from a JSON file.
import json file_name = 'example.json' with open(file_name, 'r', encoding='utf-8') as f: # โ๏ธ json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) my_data = json.loads(file_name) # ๐๏ธ Incorrectly passed file path print(my_data)
The json.load method is used to deserialize a file to a Python object, whereas the json.loads method is used to deserialize a JSON string to a Python object.
import json file_name = 'example.json' with open(file_name, 'r', encoding='utf-8') as f: my_data = json.load(f) # โ Passing the file object to json.load() print(my_data) # ๐๏ธ {'name': 'Alice', 'age': 30}
json.load()
method expects a text file or a binary file containing a JSON document that implements a .read()
method.read()
method with json.loads()
Alternatively, you manually call the read()
method on the file object and use
the json.loads()
method.
import json file_name = 'example.json' with open(file_name, 'r', encoding='utf-8') as f: # ๐๏ธ make sure to call read() my_data = json.loads(f.read()) print(my_data) # ๐๏ธ {'name': 'Alice', 'age': 30} print(type(my_data)) # ๐๏ธ <class 'dict'>
The example above achieves the same result, but instead of relying on the
json.load()
method to call read()
on the file object for us, we manually do
it and use the json.loads()
method instead.
The json.loads()
method basically helps us load a Python native object (e.g. a
dictionary or a list) from a JSON string.
json.loads()
You can try to use the str.replace()
method if you need to make your JSON
valid before using the json.loads()
method.
Here is an example JSON file that contains a single-quoted property which makes the JSON invalid.
{ "name": "Alice", 'age': 30 }
Here is how we can use the str.replace()
method to
replace the single quotes in the string with double quotes.
import json file_name = 'example.json' with open(file_name, 'r', encoding='utf-8', errors='ignore') as f: a_str = f.read() # { # "name": "Alice", # 'age': 30 ๐๏ธ Note single quotes # } print(a_str) # โ Replace single quotes with double quotes valid_json = a_str.replace("'", '"') result = json.loads(valid_json) print(result) # {'name': 'Alice', 'age': 30} print(result['name']) # Alice print(result['age']) # 30
The str.replace method returns a copy of the string with all occurrences of a substring replaced by the provided replacement.
The method takes the following parameters:
Name | Description |
---|---|
old | The substring we want to replace in the string |
new | The replacement for each occurrence of old |
count | Only the first count occurrences are replaced (optional) |
We used the replace()
method to replace all occurrences of a single quote in
the string with a double quote.
This makes the JSON valid, so we can safely use the json.loads()
method.
The JSONEncoder
class supports the conversion of the following objects and
types by default.
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float, int and float derived Enums | number |
True | true |
False | false |
None | null |
The most common causes of the "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)" error are:
text/html
) as
if it were JSON.You can learn more about the related topics by checking out the following tutorials: