[Fixed] JSONDecodeError: Expecting Value: Line 1 column 1 (char 0)

JSONDecodeError: Expecting value: line 1 column 1 (char 0) occurs while working with JSON (JavaScript Object Notation) format. You might be storing some data or trying to fetch JSON data from an API(Application Programming Interface). In this guide, we will discuss where it can creep in and how to resolve it.

How can JSONDecodeError: Expecting value: line 1 column 1 (char 0) occur?

JSONDecodeError means there is an incorrect JSON format being followed. For instance, the JSON data may be missing a curly bracket, have a key that does not have a value, and data not enclosed within double-quotes or some other syntactic error.

A JSON file example
A JSON file example

Generally, the error expecting value: line 1 column 1 (char 0) error can occur due to the following reasons.

  • Non-JSON conforming quoting
  • Empty JSON file
  • XML output (that is, a string starting with <)

Let’s elaborate on the points stated above:

1. Non-JSON conforming quoting

JSON or JavaScript Object Notation has a similar format to that of the python dictionary datatype. A dictionary requires a key or value to be enclosed in quotes if it is a string. Similarly, the JSON standard defines that keys need not be a string. However, keys should always be enclosed within double quotes. Not following this standard can also raise an error.

Keys must be double-quoted in JSON
Keys must be double-quoted in JSON

2. Empty JSON file

For this example, we have taken an empty JSON file named test.py and another file named test.py, which contains the code given below. Using context manager, we open the JSON file in reading mode and load it using the load method. However, an error is thrown because the JSON file is empty.

import json

with open("test.json", "r") as file:
    data = json.load(file)

print("Data retrieved")
Empty JSON file returns an error
Empty JSON file causes an error

3. XML output (that is, a string starting with <)

The Extensible Markup Language, or simply XML, is a simple text-based format for representing structured information: documents, data, configuration, books, transactions, invoices, and much more. Similar to JSON, it is an older way of storing data. Earlier APIs used to return data in XML format; however, JSON is nowadays the preferred choice. Let’s see how we can face the expecting value: line 1 column 1 (char 0) type error in this case.

<part number="1976">
  <name>Windscreen Wiper</name>
  <description>The Windscreen wiper
    automatically removes rain
    from your windscreen, if it
    should happen to splash there.
    It has a rubber <ref part="1977">blade</ref>
    which can be ordered separately
    if you need to replace it.
  </description>
</part>
import json
with open("test.xml", "r") as file:
    data = json.load(file)
print("Data retrieved")

Let’s break down what is happening here.

  • For ease of example, suppose API returns an XML format data, as shown above.
  • Now, when we try to load that response from API, we will get a type error.
XML response causes an error
XML response causes an error

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

1. Solution for Non-JSON conforming quoting

To resolve the type error in this case, you need to ensure that the keys and values are enclosed within the double quotes. This is necessary because it is a part of JSON syntax. It is important to realize that JSON only uses double quotes, not single quotes.

Use double quotes for enclosing keys and values
Use double quotes for enclosing keys and values

2. Solution for empty JSON file

The solution for this is self-evident in the name. To resolve the type error, in this case, make sure that the JSON file or the response from an API is not empty. If the file is empty, add content to it, and for a response from an API, use try-except to handle the error, which can be empty JSON or a 404 error, for instance.

import json
import requests


def main():
    URL = "https://api.dictionaryapi.dev/api/v2/enties/en/"
    word = input("Enter a word:")
    data = requests.get(url + word)
    data = data.text
    try:
        data_json = json.loads(data)
        print(data_json)
    except json.JSONDecodeError:
        print("Empty response")


if __name__ == "__main__":
    main()

The above code takes in a word and returns all the information related to it in a JSON format. Now in order to show how we can handle the Expecting value: line 1 column 1 (char 0) type error, we have altered the URL. entries have been changed to enties. Therefore we will get an invalid response which will not be of the JSON format. However, this is merely done to imitate the error when you might get an invalid response from an API.

  • Now, if you try to run the code above, you will be prompted to enter a word. The response is saved into the data variable and later converted to a string.
  • However, in the try block json.loads method, which parses JSON string to python dictionary raises an error.
  • This is because the response sent by API is not of JSON format, hence can’t be parsed, resulting in JSONDecodeError.
  • JSONDecodeError gets handled by the try-except block, and a “Response content is not valid JSON” gets printed as an outcome.
Response content is not valid JSON
The response content is not valid JSON
Response when everything runs correctly.
Response when everything runs correctly.

3. Solution for XML output(that is, a string starting with <)

To avoid type errors resulting from an XML format, we will convert it to a JSON format. However, firstly install this library.

pip install xmltodict
import json
import xmltodict

with open("test.xml", "r") as file:
    data = xmltodict.parse(file.read())
    file.close()

    json_data = json.dumps(data)
    with open("t.json", "w") as json_file:
        json_file.write(json_data)
        json_file.close()
print("Data retrieved")
print(data)

Let’s elaborate on the code above:

  • We have imported two libraries, namely JSON and xmltodict.
  • Using the context manager with, XML file test.xml is opened in read mode. Thereafter using the xmltodict parse method, it is converted to a dictionary type, and the file is closed.
  • json.dumps() takes in a JSON object and returns a string of that object.
  • Again using context manager with, a JSON file is created, XML data that was converted to a JSON string is written on it, and the file is closed.
xml data converted into json format
XML data converted into JSON format

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

This issue is caused by the failure of Pipenv 2018.10.9. To resolve this issue, use Pipenv 2018.5.18. For more, read here.

Are you facing this error in Flask?

Many times, when you receive the data from HTTP requests, they are fetched as bytes. So, if you face JSONDecodeError, you might be dealing with a JSON in bytes. First, you need to decode the JSON by using response.decode('utf-8'). This will create a string, and then you can parse it.

FAQs

How to parse JSON in python?

json.loads() method can be used to parse JSON in python. For instance:
import json
json_string = '{"a":"1", "b":"2", "c":"3"}'
json_to_dict = json.loads(json_string)
print(json_to_dict)
print(type(json_to_dict))

How to detect empty file/string before parsing JSON?

import os
file_path = "/home/nikhilomkar/Desktop/test.json"
print("File is empty!" if os.stat(file_path).st_size == 0 else "File isn't empty!"
)
The following code checks if the file is empty and prints the File is empty! If true, else, the File isn’t empty!.

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

The following article discussed the JSONDecodeError: Expecting value: line 1 column 1 (char 0). This error is due to various decoding and formatting errors. We looked at likely situations where it can occur and how to resolve it.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments