Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling different errors for different versions of python

Tags:

python

json

I am having issues with catching errors by the json module for different versions of Python. The json module throws a JSONDecodeError for Python 3.5.2 and ValueError for Python 2.7.12. What is the best practice for doing this?

For example, this works for Python 2.7.12

a = '{"a": [5 8]}'
try:
    d = json.loads(a)
except ValueError:
    # do something

and this works for Python 3.5.2

a = '{"a": [5 8]}'
try:
    d = json.loads(a)
except json.JSONDecodeError:
    # do something

I have seen the answer here but I want to find a more elegant way.

like image 853
Nabarun Pal Avatar asked Jul 09 '26 12:07

Nabarun Pal


1 Answers

JSONDecodeError is a subclass of ValueError:

>>> from json import JSONDecodeError
>>> issubclass(JSONDecodeError, ValueError)
True

Just stick to catching ValueError; it should suffice if you need to support both versions. All JSONDecodeError adds is a few additional fields, giving you easy access to the parsed document, and the exact position of the error.

If you need access to those attributes (provided they are present), just use hasattr() to test first:

try:
    d = json.loads(a)
except ValueError as err:
    pos = (None, None)
    if hasattr(err, lineno):
        # JSONDecodeError subclass
        pos = err.lineno, err.colno
like image 86
Martijn Pieters Avatar answered Jul 11 '26 01:07

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!