Solution For “JSONDecodeError: Expecting value: line 1 column 1 (char 0)” Error

The error JSONDecodeError: Expecting value: line 1 column 1 (char 0) is an error that is not too difficult to fix in this article. I will help you fix this error in some specific cases.

Why is JsondecodeError: expecting value: line 1 column 1 (char 0) error in Python happening?

There are many reasons to generate this error, but some common cases are trying to read, parse a non-JSON or empty JSON file, Parse a non-JSON response, get a response from a server empty, and try to parse it as a JSON, using json.loads() incorrectly,…

The error message occurs as follows:

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

In this tutorial, I will show you how to fix this error in two cases Incorrect use of json.loads() and Empty JSON file.

How to fix this error?

Case 1: Improper use of json.loads()

Example: I have a friends.json file like this:

[
        {"Alma":18},
        {"Doris":18},
        {"Lani":19}
]

Now I use json.loads() to output the program as follows:

import json
json_path = 'friends.json'
data = json.loads(json_path)

Output: 

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

The program crashes because json.loads require passing in a JSON encoded string, not a string in this example filename. I fix this error as follows:

import json
json_path = 'friends.json'

with open(json_path, 'r') as p:
    data = json.loads(p.read())

print(data)

Output:

[{"Alma":18}, {"Doris":18}, {"Lani":19}]

The with statement ensures the file is closed when the code completes. Now the program has read the JSON file.

Case 2: Empty JSON file

We have an empty JSON file named fish.json. We use json.loads() to try to read the fish.json file as follows:

import json
path = 'fish.json'

with open(path, 'r') as p:
    data = json.loads(p.read())

print(data)

Output: 

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

The fix is ​​to add data to the file but to ensure the program has the correct JSONDecodeError error. We add the try-except statement to catch this error.

Here is the file fish.json:

[
  {"Butterflyfish":5},
  {"Angelfish":5}
]

Code:

import json
path = 'fish.json'

with open(path, 'r') as f:
   try:
       data = json.loads(f.read())
       print(data)
   except json.decoder.JSONDecodeError:
       print('Empty JSON file')

Output:

[{'Butterflyfish': 5}, {'Angelfish': 5}]

I have successfully read the list of arguments in the file.

Summary

Through this article, when you encounter the error JSONDecodeError: Expecting value: line 1 column 1 (char 0), you don’t need to find it difficult anymore because I have helped you understand why you are getting this error and help you fix it in case: empty JSON file and Improper use of json.loads(). Please carefully review and follow the steps in the article to fix this error.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *