There is a rule in Python programming called "it is Easier to Ask for Forgiveness than for Permission" (in short: EAFP). It means that you should catch exceptions instead of checking values for validity.

Thus, try the following:

try:
    qByUser = byUsrUrlObj.read()
    qUserData = json.loads(qByUser).decode('utf-8')
    questionSubjs = qUserData["all"]["questions"]
except ValueError:  # includes simplejson.decoder.JSONDecodeError
    print('Decoding JSON has failed')

EDIT: Since simplejson.decoder.JSONDecodeError actually inherits from ValueError (proof here), I simplified the catch statement by just using ValueError.

Answer from Tadeck on Stack Overflow
Top answer
1 of 2
240

There is a rule in Python programming called "it is Easier to Ask for Forgiveness than for Permission" (in short: EAFP). It means that you should catch exceptions instead of checking values for validity.

Thus, try the following:

try:
    qByUser = byUsrUrlObj.read()
    qUserData = json.loads(qByUser).decode('utf-8')
    questionSubjs = qUserData["all"]["questions"]
except ValueError:  # includes simplejson.decoder.JSONDecodeError
    print('Decoding JSON has failed')

EDIT: Since simplejson.decoder.JSONDecodeError actually inherits from ValueError (proof here), I simplified the catch statement by just using ValueError.

2 of 2
55

If you don't mind importing the json module, then the best way to handle it is through json.JSONDecodeError (or json.decoder.JSONDecodeError as they are the same) as using default errors like ValueError could catch also other exceptions not necessarily connected to the json decode one.

from json.decoder import JSONDecodeError


try:
    qByUser = byUsrUrlObj.read()
    qUserData = json.loads(qByUser).decode('utf-8')
    questionSubjs = qUserData["all"]["questions"]
except JSONDecodeError as e:
    # do whatever you want

//EDIT (Oct 2020):

As @Jacob Lee noted in the comment, there could be the basic common TypeError raised when the JSON object is not a str, bytes, or bytearray. Your question is about JSONDecodeError, but still it is worth mentioning here as a note; to handle also this situation, but differentiate between different issues, the following could be used:

from json.decoder import JSONDecodeError


try:
    qByUser = byUsrUrlObj.read()
    qUserData = json.loads(qByUser).decode('utf-8')
    questionSubjs = qUserData["all"]["questions"]
except JSONDecodeError as e:
    # do whatever you want
except TypeError as e:
    # do whatever you want in this case
🌐
Python
docs.python.org › 3 › library › json.html
json — JSON encoder and decoder
2 weeks ago - JSONDecodeError – When the data being deserialized is not a valid JSON document.
Discussions

JSONDecodeError exception's message - verbose - Ideas - Discussions on Python.org
Issue One of the porposes of exception’s message is to help the developer to identify the root cause of the bug and fix it. Currently, JSONDecodeError doesn’t do it well enough. Consider the following example: import json import requests try: server_raw_response = requests.get(url) ... More on discuss.python.org
🌐 discuss.python.org
1
July 17, 2024
I get an error whenever I try to use "json.load"
This may sound stupid, but how I've enountered this before and it meant that the .json file was empty so I'm thinking that your file is not saved correctly? # Let's say that your projects contains 2 files - main.py | - doc.json (Empty) with open('doc.json', mode='r') as f: json.load(f) >> JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) More on reddit.com
🌐 r/learnpython
24
3
August 8, 2022
Help: json.loads() cannot parse valid json
File "/usr/lib/python3.7/json/__init__.py", line 348, in loads return _default_decoder.decode(s) File "/usr/lib/python3.7/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python3.7/json/decoder.py", line 353, in raw_decode obj, end = ... More on discuss.python.org
🌐 discuss.python.org
0
December 17, 2021
JSONDecodeError on Python 3.10
I am on the latest Poetry version. I have searched the issues of this repo and believe that this is not a duplicate. If an exception occurs when executing a command, I executed it again in debug mo... More on github.com
🌐 github.com
40
March 31, 2021
🌐
Career Karma
careerkarma.com › blog › python › python jsondecodeerror explanation and solution
Python JSONDecodeError Explanation and Solution | CK
December 1, 2023 - Otherwise, the program will read the data and then display the following text on the console: Equipment data has been successfully retrieved. The Python JSONDecodeError indicates there is an issue with how a JSON object is formatted.
🌐
Python.org
discuss.python.org › ideas
JSONDecodeError exception's message - verbose - Ideas - Discussions on Python.org
July 17, 2024 - Issue One of the porposes of exception’s message is to help the developer to identify the root cause of the bug and fix it. Currently, JSONDecodeError doesn’t do it well enough. Consider the following example: import json import requests try: server_raw_response = requests.get(url) server_json_response = json.loads(server_raw_response) except JSONDecodeError as error: print(error) # JSONDecodeError: Expecting , delimiter: line 1 column 23 (char 22) Can you understand what is th...
🌐
GeeksforGeeks
geeksforgeeks.org › python › json-parsing-errors-in-python
JSON Parsing Errors in Python - GeeksforGeeks
July 23, 2025 - Some common JSON parsing errors that occur in Python are: JSONDecodeError is an error that occurs when the JSON data is invalid, such as having missing or extra commas, missing brackets, or other syntax errors.
🌐
Reddit
reddit.com › r/learnpython › i get an error whenever i try to use "json.load"
r/learnpython on Reddit: I get an error whenever I try to use "json.load"
August 8, 2022 -

JSON doc:

{
    "Data" : [
        "input1",
        "input2",
        "input3",
        "input4"
    ]
}

Python code:

import json
with open("data.json", 'r') as f:
    json_data = json.load(f)
print(json_data)

Error message:

sh-5.1$ /bin/python /home/USER/Documents/Python/learning
Traceback (most recent call last):
  File "/home/USER/Documents/Python/learning", line 27, in <module>
    json_data = json.load(f)
  File "/usr/lib/python3.9/json/__init__.py", line 293, in load
    return loads(fp.read(),
  File "/usr/lib/python3.9/json/__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.9/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.9/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)

Disproved theories: Improper syntax (python), document not located, bad formatting (json), accidental empty space in json.

I get this error each time I try to use "json.load" so long as it has a valid parameter input. Whether read or write; error. I'm using Visual Studio Code on Linux Mint in case that matters.

Thanks for your time! I'll be happy to answer questions in the morning when I wake up.

EDIT: Clarity, and reddit dislikes my use of backticks. Manually tabbed code.

EDIT: This code SHOULD work. It does on other computers. But it doesn't on mine, and I don't know why nor how to fix it.

Find elsewhere
🌐
Claudia Kuenzler
claudiokuenzler.com › blog › 1394 › how-to-handle-json-decode-error-python-script-try-except
How to handle JSON decode error in Python script with try and except
February 20, 2024 - So we see the json.decoder throwing a JSONDecodeError. A common way in Python scripts is to use try + except to catch errors. The "try" part runs the code you want to run, in this case the json.loads line.
🌐
Python.org
discuss.python.org › python help
Help: json.loads() cannot parse valid json - Python Help - Discussions on Python.org
December 17, 2021 - File "/usr/lib/python3.7/json/__init__.py", line 348, in loads return _default_decoder.decode(s) File "/usr/lib/python3.7/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python3.7/json/...
🌐
Medium
medium.com › @tonycini93 › python-jsondecodeerror-67abf64e1cfe
Python — JSONDecodeError. A mistake of copying & pasting | by Tony | Medium
December 18, 2021 - JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
🌐
GitHub
github.com › python-poetry › poetry › issues › 4210
JSONDecodeError on Python 3.10 · Issue #4210 · python-poetry/poetry
March 31, 2021 - $ poetry install Installing dependencies from lock file Package operations: 16 installs, 0 updates, 0 removals • Installing sanic-routing (0.6.2): Failed JSONDecodeError Expecting value: line 1 column 1 (char 0) at /usr/local/Cellar/python@3.10/3.10.0b3/Frameworks/Python.framework/Versions/3.10/lib/python3.10/json/decoder.py:355 in raw_decode 351│ """ 352│ try: 353│ obj, end = self.scan_once(s, idx) 354│ except StopIteration as err: → 355│ raise JSONDecodeError("Expecting value", s, err.value) from None 356│ return obj, end 357│
Author   robd003
Top answer
1 of 3
11

Looking at the documentation for this API it seems the only responses are in JSON format, so receiving HTML is strange. To increase the likelihood of receiving a JSON response, you can set the 'Accept' header to 'application/json'.

I tried querying this API many times with parameters and did not encounter a JSONDecodeError. This error is likely the result of another error on the server side. To handle it, except a json.decoder.JSONDecodeError in addition to the ConnectionError error you currently except and handle this error in the same way as the ConnectionError.

Here is an example with all that in mind:

import requests, json, time, random

def get_submission_records(client, since, try_number=1):
    url = 'http://reymisterio.net/data-dump/api.php/submission?filter[]=form,cs,'+client+'&filter[]=date,cs,'+since
    headers = {'Accept': 'application/json'}
    try:
        response = requests.get(url, headers=headers).json()
    except (requests.exceptions.ConnectionError, json.decoder.JSONDecodeError):
        time.sleep(2**try_number + random.random()*0.01) #exponential backoff
        return get_submission_records(client, since, try_number=try_number+1)
    else:
        return response['submission']['records']

I've also wrapped this logic in a recursive function, rather than using while loop because I think it is semantically clearer. This function also waits before trying again using exponential backoff (waiting twice as long after each failure).

Edit: For Python 2.7, the error from trying to parse bad json is a ValueError, not a JSONDecodeError

import requests, time, random

def get_submission_records(client, since, try_number=1):
    url = 'http://reymisterio.net/data-dump/api.php/submission?filter[]=form,cs,'+client+'&filter[]=date,cs,'+since
    headers = {'Accept': 'application/json'}
    try:
        response = requests.get(url, headers=headers).json()
    except (requests.exceptions.ConnectionError, ValueError):
        time.sleep(2**try_number + random.random()*0.01) #exponential backoff
        return get_submission_records(client, since, try_number=try_number+1)
    else:
        return response['submission']['records']

so just change that except line to include a ValueError instead of json.decoder.JSONDecodeError.

2 of 3
0

Catching ValueError is universal across python versions from py2 to py3

For py3 only is better to catch from already imported requests library: requests.JSONDecoderError, so you don't need to import json library.

🌐
Techstaunch
techstaunch.com › blogs › json-decoder-jsondecodeerror-expecting-value-line-1-column-1-char-0-how-to-solve
json.decoder.jsondecodeerror: expecting value: line 1 column 1 (char 0) How to Fix, Solve
August 21, 2024 - Q.How to fix JSON parse error in Python? A.If something is wrong (a missing parentheses or quotes for example) it will use a few simple heuristics to fix the JSON string: Add the missing parentheses if the parser believes that the array or object should be closed. Quote strings or add missing single quotes. Adjust whitespaces and remove line breaks. The JSONDecodeError might seem daunting at first, but with proper error handling and validation, you can build robust applications that handle JSON data reliably.
🌐
GeeksforGeeks
geeksforgeeks.org › python › orjson-jsondecodeerror-in-python
orjson.JSONDecodeError in Python - GeeksforGeeks
July 23, 2025 - In this example, we attempt to read JSON data from a non-existent file. As expected, FileNotFoundError is raised, indicating that the file does not exist. However, if the file existed but contained invalid JSON data, orjson.JSONDecodeError would be raised instead.
🌐
LSEG Developer Community
community.developers.refinitiv.com › home › eikon data apis
JSONDecodeError in Python API - LSEG Developer Community
June 29, 2020 - When I try to retrieve data using the Pyhon API, I get a JSONDecodeError. I am using Python 3.8.5 (64-bit) on Windows 10 and version 1.1.6.post3 of the eikon package. The same code worked fine, i.e. produced the expected results, a couple of months ago. I updated the eikon package after I got ...
🌐
Atlassian Community
community.atlassian.com › q&a › jira › questions › getting json.decoder.jsondecodeerror while trying to get all jira users using python script
Getting json.decoder.JSONDecodeError while trying to get all JIRA users using Python Script
September 7, 2022 - Hi All, I am getting the "json.decoder.JSONDecodeError" when I am trying to fetch all jira users using the below python script. Here is the code snippet: Here is the error snippet: I tried to find the solution on the Atlassian Community as well as Stackoverflow. Couldn't find any possible solutio...
🌐
DeepLearning.AI
community.deeplearning.ai › short course q&a › ai agents in langgraph
JSONDecodeError in Lesson 3 - AI Agents in LangGraph - DeepLearning.AI
March 17, 2024 - Here is the code block… import json from pygments import highlight, lexers, formatters # parse JSON parsed_json = json.loads(data.replace("'", '"')) # pretty print JSON with syntax highlighting formatted_json = json.d…
🌐
GitHub
github.com › langchain-ai › langchain › issues › 12180
JSONDecodeError on Cookbook/Semi_structured_multi_mudal_RAG_LLaMA2.ipynb · Issue #12180 · langchain-ai/langchain
October 24, 2023 - 335 336 """ --> 337 obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 338 end = _w(s, end).end() File ~/anaconda3/envs/langchain/lib/python3.8/json/decoder.py:355, in JSONDecoder.raw_decode(self, s, idx) 354 except StopIteration as err: --> 355 raise JSONDecodeError("Expecting value", s, err.value) from None 356 return obj, end JSONDecodeError: Expecting value: line 1 column 1 (char 0) During handling of the above exception, another exception occurred: JSONDecodeError Traceback (most recent call last) Cell In[6], line 3 1 # Apply to text 2 texts = [i.text for i in text_elements if i.text != ""
Author   Lin Wang(MrLinWang)
🌐
Python.org
discuss.python.org › python help
So I am editing a simple python program and I get this error, WHY? - Python Help - Discussions on Python.org
March 5, 2024 - So I installed this simple python program that floods your ISP with random data. All the websites that it pulls from are listed in the config file. So I opened the config file to edit the list of websites and after editing the websites and running the program, it returns with this error from ...
🌐
Python.org
discuss.python.org › python help
Hello, i need help with the code. I need read code of JSON, but I have a problem - Python Help - Discussions on Python.org
December 16, 2023 - with open(‘new_york_times.json’,mode=“+r”,encoding=“UTF-8”) as contenido: set_datos = json.load(contenido) df = pd.DataFrame.from_dict(set_datos) But i get this error: Traceback (most recent call last): File “c:\Users\aquiroz\OneDrive - Unified Networks\Documentos\adi VS\jsob.py”, line 14, in set_datos = json.load(contenido) ^^^^^^^^^^^^^^^^^^^^ File “C:\Users\aquiroz\AppData\Local\Programs\Python\Python312\Lib\json_init_.py”, line 293, in load return loads(fp.read(), ^^^^^^^^^^^^^^^^ ...