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 encoder and decoder — Python 3.14.3 documentation
4 weeks ago - As a result of this, if a dictionary is converted into JSON and then back into a dictionary, the dictionary may not equal the original one. That is, loads(dumps(x)) != x if x has non-string keys.
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… More on discuss.python.org
🌐 discuss.python.org
1
July 17, 2024
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
0
December 17, 2021
response.json() raises inconsistent exception type
There are some comments about this on #4842 but I think it warrants its own issue. If simplejson is present in the environment, the library uses it so .json() returns simplejson.errors.JSONDecodeEr... More on github.com
🌐 github.com
10
April 16, 2021
How to get error location from json.loads in Python - Stack Overflow
I think it would be nicer if the json parser returned a more qualified Exception which contains these fields. I have opened an issue for it. More on stackoverflow.com
🌐 stackoverflow.com
🌐
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.

🌐
Medium
medium.com › @saifulj1234 › handling-errors-exceptions-and-manipulating-json-data-in-python-2900353cca1f
Handling Errors, Exceptions and Manipulating JSON data in Python | by Saiful Rahman | Medium
July 23, 2022 - So we can use json.dump() and json.load() to serialize and deserialize data from JSON format to Python dictionary format and it allows us to interchange information. we can change it into a JSON format to store it and then we can take back out of storage and turn it into a Python dictionary to easily work with it in our code. Using these functions and error exception methods, I have improved my previous project in the Password Manager program to store data in JSON format.
🌐
GeeksforGeeks
geeksforgeeks.org › python › json-parsing-errors-in-python
JSON Parsing Errors in Python - GeeksforGeeks
July 23, 2025 - Python · import json # Missing ... 'Om Mishra', 'age': 22, 'city': 'Ahmedabad'} KeyError is an error that occurs when the JSON data does not contain the expected key....
🌐
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 - Luckily my toot (a post on Mastodon) received a few comments and hints and it turns out that JSONDecodeError is indeed an error which can be used in the exception handling. However the error handler JSONDecodeError does not exist in the "global" namespace of the Python script and needs to be called from the json module: try: data = json.loads(output) except json.JSONDecodeError as e: print("Error: Unable to decode JSON, Error: {}. Manually run command ({}) to verify JSON output.".format(e, cmd))
🌐
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...
🌐
Python.org
discuss.python.org › python help
Help: json.loads() cannot parse valid json - Python Help - Discussions on Python.org
December 17, 2021 - python code: import json x = json.loads('{"message":"variable `z` is assigned to, but never used","code":{"code":"unused_variables","explanation":null},"level":"warning","spans":[{"file_name":"main.rs","byte_start":191,…
Find elsewhere
🌐
GitHub
github.com › psf › requests › issues › 5794
response.json() raises inconsistent exception type · Issue #5794 · psf/requests
April 16, 2021 - There was an error while loading. Please reload this page. ... There are some comments about this on #4842 but I think it warrants its own issue. If simplejson is present in the environment, the library uses it so .json() returns simplejson.errors.JSONDecodeError rather than json.decoder.JSONDecodeError · If I'm writing a library that uses requests I don't know what other libraries will be present in an environment. I expect that a method returns a consistent exception type that I can handle.
Author   rowanseymour
🌐
ProgramCreek
programcreek.com › python › example › 95917 › json.JSONDecodeError
Python Examples of json.JSONDecodeError
def test_request_sources_error(status_code, error, error_body, caplog): responses.add( responses.POST, '{}/api/v1/requests'.format(CACHITO_URL), content_type='application/json', body=error_body, status=status_code, ) with pytest.raises(error): CachitoAPI(CACHITO_URL).request_sources(CACHITO_REQUEST_REPO, CACHITO_REQUEST_REF) try: response_data = json.loads(error_body) except ValueError: # json.JSONDecodeError in py3 assert 'Cachito response' not in caplog.text else: response_json = 'Cachito response:\n{}'.format(json.dumps(response_data, indent=4)) # Since Python 3.7 logger adds additional whitespaces by default -> checking without them assert re.sub(r'\s+', " ", response_json) in re.sub(r'\s+', " ", caplog.text) Example #6 ·
Top answer
1 of 4
10

[This answer is outdated. See other answers for modern python versions]

Scanning the json/decoder.py source code, we can see that the decoder's error messages are constructed using the errmsg function:

Copydef errmsg(msg, doc, pos, end=None):
    # Note that this function is called from _json
    lineno, colno = linecol(doc, pos)
    if end is None:
        fmt = '{0}: line {1} column {2} (char {3})'
        return fmt.format(msg, lineno, colno, pos)
        #fmt = '%s: line %d column %d (char %d)'
        #return fmt % (msg, lineno, colno, pos)
    endlineno, endcolno = linecol(doc, end)
    fmt = '{0}: line {1} column {2} - line {3} column {4} (char {5} - {6})'
    return fmt.format(msg, lineno, colno, endlineno, endcolno, pos, end)
    #fmt = '%s: line %d column %d - line %d column %d (char %d - %d)'
    #return fmt % (msg, lineno, colno, endlineno, endcolno, pos, end)

Since this is a pure-python module, it's easy to wrap this function with a custom one. This process is known as monkey patching:

Copyimport json

original_errmsg= json.decoder.errmsg

def our_errmsg(msg, doc, pos, end=None):
    json.last_error_position= json.decoder.linecol(doc, pos)
    return original_errmsg(msg, doc, pos, end)

json.decoder.errmsg= our_errmsg

try:
    data = json.loads('{1:}')
except ValueError as e:
    print("error at", json.last_error_position)

Obviously, this solution is not ideal, since the implementation may change at any time, although it's still better than relying on the message. You should check if errmsg exists before patching (and possibly if there's no other arguments, or use varargs).

2 of 4
5

If you use simplejson library, you get a well qualified JSONDecodeError:

Copyclass JSONDecodeError(ValueError):
   """Subclass of ValueError with the following additional properties:

   msg: The unformatted error message
   doc: The JSON document being parsed
   pos: The start index of doc where parsing failed
   end: The end index of doc where parsing failed (may be None)
   lineno: The line corresponding to pos
   colno: The column corresponding to pos
   endlineno: The line corresponding to end (may be None)
   endcolno: The column corresponding to end (may be None)

   """

Hopefully, this will be merged into stdlib soon.

🌐
Career Karma
careerkarma.com › blog › python › python jsondecodeerror explanation and solution
Python JSONDecodeError Explanation and Solution | CK
December 1, 2023 - A Python JSONDecodeError indicates there is an issue with the way in which your JSON data is formatted. For example, your JSON data may be missing a curly bracket, or have a key that does not have a value, or be missing some other piece of syntax.
🌐
GitHub
github.com › Adyen › adyen-python-api-library › issues › 43
Unhandled exceptions on json.loads give no clues on connection errors to Adyen · Issue #43 · Adyen/adyen-python-api-library
November 24, 2017 - To make the problem worse this exception tell us nothing about what we are sending and receiving to Adyen servers, and so we can't investigate the problem because we have no clues about it. We need that devs handle the json_lib.loads call at https://github.com/Adyen/adyen-python-api-library/blob/1.1.0/Adyen/client.py#L413 and instead ValueError return an AdyenInvalidRequestError with request information so we can investigate the problem.
Author   felipe-prenholato
🌐
Amandinemlee
amandinemlee.com › 2017 › 03 › 20 › Python-exception-handling
Python Exception Handling - Amandine Lee
The program was executed in Python 3 and this is Python 2. However, there are plenty of places where the distinction between these possibilities doesn’t seem particularly obvious. Did the callee raise an error because it failed, or because I violated its assumptions? Or did I pass through a violated assumption from my caller? In the examples above, IOError would be raised by json.loads(filename), regardless of whether the filename didn’t exist (probably the caller’s problem) or the disk was broken (the callee’s problem, since the ultimate callee of any software is hardware).
🌐
Python Clear
pythonclear.com › home › errors › 2 easy fixes for valueerror: no json object could be decoded
2 Easy fixes for Valueerror: No JSON Object Could be Decoded - Python Clear
January 27, 2023 - ValueError: no JSON object could be decoded error is a type of exception error caused when a file object is called with a JSON.load() or when a string containing the attached JSON code is called with a JSON.loads(). ValueError: no JSON object ...
🌐
Medium
lynn-kwong.medium.com › python-json-tricks-how-to-deal-with-jsondecodeerror-2353464814bc
Python JSON tricks: how to deal with JSONDecodeError | by Lynn G. Kwong | Medium
October 31, 2024 - A JSON looks like the dictionary type in Python, but they are different. The essential difference is that a JSON is a pure string that has a strict format. If you don’t write it properly, you may have unexpected errors.
🌐
Python Forum
python-forum.io › thread-41469.html
json loads throwing error
January 21, 2024 - Hi All, I have python code written using netmiko library which does SSH to a switch and run the command 'show env power | json'. I need to convert this out put to json format so that I can track individual keys to check the power supply status. aris...
🌐
Bobby Hadz
bobbyhadz.com › blog › python-jsondecodeerror-extra-data
json.decoder.JSONDecodeError: Extra data in Python [Solved] | bobbyhadz
April 8, 2024 - The Python "json.decoder.JSONDecodeError: Extra data" occurs when we try to parse multiple objects without wrapping them in an array. To solve the error, wrap the JSON objects in an array or declare a new property that points to an array value ...
🌐
GitHub
github.com › psf › requests › issues › 1665
Error in JSON decoding for Python 3 · Issue #1665 · psf/requests
October 12, 2013 - This happens whenever you try to feed a bytestring into the JSON decoder. For a simple test case (and remember, this is only in Python 3): ... It seems like as long as requests just dumps the loaded bytestrings directly into the decoder, without ...
Author   MaddieM4