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
3 weeks ago - >>> # Neither of these calls raises an exception, but the results are not valid JSON >>> json.dumps(float('-inf')) '-Infinity' >>> json.dumps(float('nan')) 'NaN' >>> # Same when deserializing >>> json.loads('-Infinity') -inf >>> json.loads('NaN') nan · In the serializer, the allow_nan parameter can be used to alter this behavior. In the deserializer, the parse_constant parameter can be used to alter this behavior. The RFC specifies that the names within a JSON object should be unique, but does not mandate how repeated names in JSON objects should be handled.
Discussions

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
Handling json.loads() Value Error in python - Stack Overflow
NaN is not a valid JSON symbol, ... support load of nan/inf. See https://github.com/ultrajson/ultrajson/issues/146 for more info · In my opinion attempt to replace nan with null is prone to errors. use json from Standard Library. Here is link to relevant part of the docs ... The best options is to use jsonpickle to serialize the numpy values properly. import jsonpickle import jsonpickle.ext.numpy as jsonpickle_numpy jsonpickle_numpy.register_handlers() with ... More on stackoverflow.com
🌐 stackoverflow.com
How to get error location from json.loads in Python - Stack Overflow
When I use json.loads in Python 3 and catch any resulting errors, like: More on stackoverflow.com
🌐 stackoverflow.com
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
🌐
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 - 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. The "except" part handles a potential error of the try part.
🌐
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 - Getting Started with Python Part-17 Handling Errors, Exceptions and Manipulating JSON data in Python In this article, I gonna summarize some advanced topics in Python such as errors and exceptions. I …
🌐
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.

🌐
Career Karma
careerkarma.com › blog › python › python jsondecodeerror explanation and solution
Python JSONDecodeError Explanation and Solution | CK
December 1, 2023 - Alternatively, we could use a try…except handler to handle this issue so that our code will not immediately return an error if we face another formatting issue: import json try: with open("equipment.json") as file: data = json.load(file) print("Equipment data has been successfully retrieved.") except json.decoder.JSONDecodeError: print("There was a problem accessing the equipment data.")
🌐
Stack Overflow
stackoverflow.com › questions › 64182380 › handling-json-loads-value-error-in-python
Handling json.loads() Value Error in python - Stack Overflow
NaN is not a valid JSON symbol, see the spec at http://json.org/ ujson does not support load of nan/inf. See https://github.com/ultrajson/ultrajson/issues/146 for more info · In my opinion attempt to replace nan with null is prone to errors. use json from Standard Library. Here is link to relevant part of the docs ... The best options is to use jsonpickle to serialize the numpy values properly. import jsonpickle import jsonpickle.ext.numpy as jsonpickle_numpy jsonpickle_numpy.register_handlers() with open('file.json', 'wb') as _file: _file.write(jsonpickle.encode(pairs).encode()) with open('file.json', 'rb') as _file: unpacked = jsonpickle.decode(_file.read())
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.

Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › json-parsing-errors-in-python
JSON Parsing Errors in Python - GeeksforGeeks
April 23, 2025 - 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. This error is typically raised by the json.loads() function when it's unable to parse the JSON data.
🌐
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,…
🌐
Bobby Hadz
bobbyhadz.com › blog › python-jsondecodeerror-extra-data
json.decoder.JSONDecodeError: Extra data in Python [Solved] | bobbyhadz
April 8, 2024 - One way to solve the error is to wrap the objects in an array and separate them by a comma. ... Notice that we wrapped the objects in square brackets to create a JSON array. Make sure to separate the objects in the array by a comma.
🌐
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...
🌐
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 - Sometimes we have big periods of time that we get following error from Adyen client: ValueError('No JSON could be decoded') 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
🌐
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.
🌐
Reddit
reddit.com › r/learnpython › json.loads throws an error i don't understand
r/learnpython on Reddit: json.loads throws an error I don't understand
June 23, 2022 -

I'm completely new to using the python json library, and I'm not sure how to interpret an error message. In my code, I'm calling json.loads() on a (albeit awfully complex) string, and it doesn't seem to like my input. Here's the string it's called on:

[[{"@context":"http://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"https://people.com/","name":"Home","image":None}},{"@type":"ListItem","position":2,"item":{"@id":"https://people.com/celebrity/","name":"Celebrity","image":None}},{"@type":"ListItem","position":3,"item":{"@id":"https://people.com/parents/","name":"Parents","image":None}}]},{"@context":"http://schema.org","@type":"NewsArticle","headline":"Meet+the+Man+Behind+Daddy+Pig:+Richard+Ridings+on+'Keeping+the+Magic+Alive'+for+18+Years","image":[{"@type":"ImageObject","url":"https://imagesvc.meredithcorp.io/v3/mm/image?url=https%3A%2F%2Fstatic.onecms.io%2Fwp-content%2Fuploads%2Fsites%2F20%2F2022%2F07%2F28%2Fdaddy-pig-richard-ridings-072822.jpg","width":1500,"height":1000},{"@type":"ImageObject","url":"https://imagesvc.meredithcorp.io/v3/mm/image?url=https%3A%2F%2Fstatic.onecms.io%2Fwp-content%2Fuploads%2Fsites%2F20%2F2022%2F07%2F28%2Fpeppa-pig-daddy-pig-072822.jpg"}],"author":[{"@type":"Person","name":"Georgia+Slater","url":"https://people.com/author/georgia-slater/","sameAs":["https://twitter.com/georgiahslater"]}],"publisher":{"@type":"Organization","name":"PEOPLE.com","url":"https://people.com","logo":{"@type":"ImageObject","url":"https://people.com/img/logo.png","width":120,"height":60},"sameAs":["https://www.facebook.com/peoplemag","https://twitter.com/people","https://www.pinterest.com/people/","https://www.instagram.com/people/","https://www.youtube.com/user/people","https://www.snapchat.com/discover/People-Magazine/0407249978"]},"datePublished":"2022-07-29T18:50:22-05:00","dateModified":"2022-07-29T18:50:22-05:00","description":"Richard+Ridings+has+been+voicing+the+beloved+character+Daddy+Pig+on+the+popular+children's+show+<em>Peppa+Pig</em>+for+nearly+two+decades+—+and+he's+not+stopping+anytime+soon","mainEntityOfPage":"https://people.com/parents/daddy-pig-richard-ridings-on-keeping-the-magic-alive-for-18-years-exclusive/"}]]

and here's the error I get:

Traceback (most recent call last):
  File "/Users/achatterjee/Documents/MITM Analysis/test_flatten.py", line 3, in <module>
    print(json.loads(string1))
  File "/Users/achatterjee/opt/anaconda3/lib/python3.9/json/__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "/Users/achatterjee/opt/anaconda3/lib/python3.9/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/Users/achatterjee/opt/anaconda3/lib/python3.9/json/decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 4 (char 3)

I'm not entirely sure how to interpret this error, as I'm new to using the json library. Any and all help is very much appreciated, thank you.

🌐
Stack Overflow
stackoverflow.com › questions › 64129301 › error-handling-for-bad-values-in-json-loading
python - Error handling for bad values in JSON loading - Stack Overflow
for file in [self._metadata_file_name, self._pharses_map_file_name]: with open(file) as json_file: for line in json_file: try: row = json.loads(line) if row: if file == self._metadata_file_name: self._metdata = {**self._metdata, **row} else: self._pharses_map = {**self._pharses_map, **row} except Exception as e: self._logger.log(message="Error pasring JSON " + line + ", for model: " + self._mode + ", file: " + self._metadata_file_name, error=str(e), metadata={"mode" : self._mode}, logType=self._logger.LOG_TYPE_ERROR)
🌐
Analytics Vidhya
analyticsvidhya.com › home › python json.loads() and json.dump() methods
Python json.loads() and json.dump() methods - Analytics Vidhya
May 1, 2025 - The json.loads() function raises a ValueError if the input JSON string is not valid. To handle this error, we can use a try-except block.
🌐
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...