JSONDecodeError: Expecting value: line 1 column 1 (char 0)

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
8 min

banner

# JSONDecodeError: Expecting value: line 1 column 1 (char 0)

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.

# Trying to parse an empty string causes the error

Here is a very simple example of how the error occurs.

main.py
import json # โ›”๏ธ json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) result = json.loads('')

parsing an empty string

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.

main.py
import json my_str = '' try: result = json.loads(my_str) except json.decoder.JSONDecodeError: # ๐Ÿ‘‡๏ธ this runs print('The string does NOT contain valid JSON')

handle exception using try except

If an error is raised, the except block runs.

The same can be done when reading from a file.

main.py
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')

using try except to solve error when reading file

# Common causes of the error

The most common causes of the error are:

  • Trying to parse invalid JSON values (e.g. single-quoted or with a trailing comma).
  • Getting an empty response from a remote server (e.g. 204 or 404) and trying to parse it as if it were JSON.
  • Trying to parse a response with a different Content-Type (e.g. text/html) as if it were JSON.
  • Trying to read a JSON file incorrectly or trying to parse the contents of an empty JSON file.

# Trying to parse invalid JSON values

Here is an example of a file that stores invalid JSON.

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

main.py
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)

make sure to double quote json properties

To solve the error, make sure to wrap all keys and string values in your JSON in double quotes.

example.json
{ "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.

main.py
# โœ… 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

error resolved after double quoting property

Make sure to set the encoding keyword argument when opening the file (as shown in the code sample above).

# Forgetting to wrap a property or string value in quotes

Here are some examples of invalid and valid JSON values.

example.json
// โ›”๏ธ 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.

example.json
// โœ… 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.

# Using single quotes instead of double quotes for properties or values

Make sure that no properties or string values are wrapped in single quotes.

example.json
// โ›”๏ธ 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.

example.json
// โœ… Valid JSON (property names and values are double-quoted) { "name": "Alice", "age": 30 }

# Make sure you don't have trailing commas

Having a trailing comma after the last element of an array or the last key-value pair makes your JSON invalid.

example.json
// โ›”๏ธ 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.

example.json
// โœ… Valid JSON (no trailing commas) { "name": "Alice", "age": 30 }

# Getting an empty response when making an HTTP request

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.

main.py
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:

  1. The response status is not 204 (No content).
  2. The response headers dictionary has a content-type key.
  3. The value of the 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).

# Make sure the API doesn't respond with an incorrect Content-Type

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.

# Trying to read an empty JSON file or reading a JSON file incorrectly

The error is often caused when:

  1. Trying to read a JSON file incorrectly.
  2. Trying to read an empty JSON file.
  3. Trying to read a JSON file that contains invalid JSON.

You can use the json.load() method to deserialize a JSON file to a Python object.

main.py
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}

read json file correctly

The example assumes that there is a file called example.json located in the same directory.

example.json
{"name": "Alice", "age": 30}

Make sure that the file that you are reading from is not empty as that often causes the error.

# Using a try/except statement to handle a potential error

If your file may contain invalid JSON, use a try/except statement to handle the error.

Let's say we have the following JSON file.

example.json
{ "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.

main.py
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')

using try except when reading json file

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.

# Make sure to not pass the file path to 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.

main.py
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)

passing file path to json loads

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.

main.py
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}

using json load method correctly

The json.load() method expects a text file or a binary file containing a JSON document that implements a .read() method.

# Manually calling the read() method with json.loads()

Alternatively, you manually call the read() method on the file object and use the json.loads() method.

main.py
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'>

manually calling read with json load

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.

# Trying to make your JSON valid before using 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.

example.json
{ "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.

main.py
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

replace single with double quotes before parsing json

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:

NameDescription
oldThe substring we want to replace in the string
newThe replacement for each occurrence of old
countOnly 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.

PythonJSON
dictobject
list, tuplearray
strstring
int, float, int and float derived Enumsnumber
Truetrue
Falsefalse
Nonenull

# Things that commonly cause the error

The most common causes of the "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)" error are:

  • Trying to parse invalid JSON values (e.g. single-quoted or with a trailing comma).
  • Getting an empty response from a remote server (e.g. 204 or 404) and trying to parse it as if it were JSON.
  • Trying to parse a response with a different Content-Type (e.g. text/html) as if it were JSON.
  • Trying to read a JSON file incorrectly or trying to parse the contents of an empty JSON file.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev