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
🌐
Python
docs.python.org › 3 › library › json.html
JSON encoder and decoder — Python 3.14.3 documentation
3 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.
🌐
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,…
Discussions

python - Handle JSON Decode Error when nothing returned - Stack Overflow
I am parsing json data. I don't have an issue with parsing and I am using simplejson module. But some api requests returns empty value. Here is my example: { "all" : { "count" : 0, "quest... More on stackoverflow.com
🌐 stackoverflow.com
Python json.loads() returns JSONDecodeError - Stack Overflow
But when I try to convert it into a python dictionary using json.loads(), I get the following error: 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
Python json.loads doesn't work - Stack Overflow
I've been trying to figure out how to load JSON objects in Python. def do_POST(self): length = int(self.headers['Content-Length']) decData = str(self.rfile.read(length)) print decData, type(decData) "{'name' : 'journal2'}" postData = json.loads(decData) print postData, type(postData) #{'name' : 'journal2'} postData = json.loads(postData) print postData, type(postData) # Error... 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.

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

🌐
Python.org
discuss.python.org › python help
Help: json.loads() cannot parse valid json - Page 2 - Python Help - Discussions on Python.org
May 14, 2022 - Yeah, here is a real example I’m struggling with. It’s absolutely the same string 🙂 import json dummy_response = '{"overriding_parameters": {"jar_params": ["{\"aggregationType\":\"Type1\",\"startDate\":\"2022-05-10\",\"endDate\":\"2022-05-10\"}"]}}' json.loads(r'{"overriding_parameters": {"jar_params": ["{\"aggregationType\":\"Type1\",\"startDate\":\"2022-05-10\",\"endDate\":\"2022-05-10\"}"]}}') # works fine - test it out json.loads(dummy_response) # raises JSONDecodeError print(d...
Find elsewhere
🌐
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.
Top answer
1 of 3
13

Your JSON data is enclosed in extra quotes making it a JSON string, and the data contained within that string is not JSON.

Print repr(decData) instead, you'll get:

'"{\'name\' : \'journal2\'}"'

and the JSON library is correctly interpreting that as one string with the literal contents {'name' : 'journal2'}. If you stripped the outer quotes, the contained characters are not valid JSON, because JSON strings must always be enclosed in double quotes.

For all the json module is concerned, decData could just as well have contained "This is not JSON" and postData would have been set to u'This is not JSON'.

>>> import json
>>> decData = '''"{'name' : 'journal2'}"'''
>>> json.loads(decData)
u"{'name' : 'journal2'}"
>>> json.loads(json.loads(decData))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 326, in loads
    return _default_decoder.decode(s)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 1 (char 1)

Fix whatever is producing this string, your view is fine, it's the input that is broken.

2 of 3
6

To workaround the error 'Expecting property name enclosed in double quotes' you can do:

import json
data = "{'name' : 'journal2'}"
json.loads(json.dumps(data))
🌐
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 - 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))
🌐
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.

🌐
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...
🌐
Python.org
discuss.python.org › python help
Why i am receiving the below error message? - Python Help - Discussions on Python.org
July 9, 2021 - Python code: import json import csv with open("/Users/olicaluag/Desktop/capture_for_Oliver.txt") as file: data = jason.load(file) fname = “output.csv” with open(fname, “w”) as file: csv_file = csv.writer(file) csv_file.writerow([“Interface”, “Logs”, “Name”]) for item in data[“result”]: csv_file.writerow([item[‘interface’], item[‘logs’], item[‘name’]]) error message: Traceback (most recent call last): File “/Users/olicaluag/Desktop/Hello World1.py”, line 5, in data = jason.load(fil...
🌐
Stack Overflow
stackoverflow.com › questions › 39650441 › python-json-loads-failing-to-parse-json-string
falconframework - Python json.loads() failing to parse json string - Stack Overflow
This code was working fine 9 months ago but currently throws the error: "list indices must be integers or slices, not str." I think it likely broke after a Python or Falcon package update. The ouput of raw_json.decode('utf-8') looks ok, returning [{"w": "10.191.0.2", "c": "10.191.0.3", "l": "255.255.255.0", "t": "4"}]. I think json.loads() is the root of my problem.
🌐
Dot Net Perls
dotnetperls.com › json-python
Python - json: Import JSON, load and dumps - Dot Net Perls
import json # An error occurs when the JSON is invalid. result = json.loads('["invalid JSON data sorry')
🌐
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 - Python version: 2.7.12 Library version: 1.1.0, 1.2.0, development Description · 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