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

🌐
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,…
🌐
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
Find elsewhere
🌐
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
June 21, 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
🌐
Python Forum
python-forum.io › thread-41469.html
json loads throwing error
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...
🌐
Amandinemlee
amandinemlee.com › 2017 › 03 › 20 › Python-exception-handling
Python Exception Handling
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 ...
🌐
Bobby Hadz
bobbyhadz.com › blog › python-jsondecodeerror-extra-data
json.decoder.JSONDecodeError: Extra data in Python [Solved] | bobbyhadz
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 ...
🌐
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.
Top answer
1 of 2
10

User input sucks. You can't trust those users to get anything right, and so you've got to handle all kinds of special cases that make your life difficult. Having said that, we can minimize the difficulty with general principles.

Validate early, not often

Check input for validity as soon as it read into your program. If you read in a string that should be a number, convert it into a number right away and complain to the user if it isn't a number. Any rogue data you don't verify at input will make its way into the rest of the program and produce bugs.

Now, you can't always do this. There will be cases where you can't verify the correct properties right away, and you'll have to verify them during later processing. But you want as much verification to happen as early as possible so that you have your special cases around input logic centralized to one location as much as possible.

Use Schemas

Let's consider a function that parses some json.

def parse_student(text):
    try: 
        data = json.parse(text)
    except ValueError as error:
        raise ParseError(error)

    if not isinstance(data, dict):
        raise ParseError("Expected an object!")
    
    try:
        name = data['name']
    except KeyError:
        raise ParseError('Expected a name')

    if not isinstance(name, dict):
       raise ParseError("Expected an object for name")

    try:
        first = name['first']
    except KeyError:
        raise ParseError("Expected a first name")
    
    if not isinstance(first, basestring):
        raise ParseError("Expected first name to be a string")
    
    if first == '':
        raise ParseError("Expected non-empty first name")

That was a lot of work just to extract the first name, let alone any other attributes. We can make this a lot better if we can use a json-schema. See: http://json-schema.org/.

I can describe what my student object looks like:

{
    "type": "object",
    "properties": {
        "name": {
            "type": "object",
            "properties": {
                  "first" : {
                       "type" : "string"
                  }
            },
            "required": "first"
        },
    } 
    "required": ["name"]
}

When I parse I then do something like:

def parse_student(text):
    try: 
        data = json.parse(text)
    except ValueError as error:
        raise ParseError(error)

    try:
        validate(data, STUDENT_SCHEMA)
    except ValidationError as error:
        raise ParseError(error)

    first = data['name']['first']

Checking against the schema verifies most of the structure that I need. If the user input does not match the schema, the schema validator will produce a nice error message explaining exactly what was wrong. It will do so far more consistently and correctly then if I wrote the checking code by hand. Once the validation has been passed, I can just grab data out of the json object, because I know that it will have the correct structure.

Now, you probably aren't parsing JSON. But you may find that you can do something similar for your format that lets you reuse the basic validation logic across the different pieces of information that you fetch.

2 of 2
2

You can probably simplify your code by centralising the try/except validation of function args, and the conversion of exceptions to your exception class, into one or two decorators, which you apply to each of your methods and functions. google for python decorators for exceptions, and python decorators to validate args and you'll find stackoverflow examples like this and this.

You often don't need to explicitly validate method arguments as your code is going to cause exceptions naturally, and this might be good enough, as you cannot test for all eventualities.

Remember when writing a script, that often that your code will be even more useful if someone can include it as a library module, so make the main be specific to what a user would like from the command line, but in the library part don't try too hard to obscure where an exception stems from and so on.