Handling different errors for different python versions
I'm having trouble catching module errors json
for different Python versions. The module json
issues a JSONDecodeError
for Python 3.5.2
and ValueError
for Python 2.7.12
. What's the best practice for 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 saw the answer here , but I want to find a more elegant way.
source to share
JSONDecodeError
is a subclass ValueError
:
>>> from json import JSONDecodeError
>>> issubclass(JSONDecodeError, ValueError)
True
Just stick to catching ValueError
; this should be sufficient if you need to support both versions. All JSONDecodeError
adds a few extra fields, giving you easy access to the document being parsed and the exact location of the error.
If you need access to these attributes (if present), just use hasattr()
to check:
try:
d = json.loads(a)
except ValueError as err:
pos = (None, None)
if hasattr(err, lineno):
# JSONDecodeError subclass
pos = err.lineno, err.colno
source to share
For a module json
in particular, which is mostly simplejson
packaged as a json
module and distributed with Python, you can use the latest (or at least the same) version simplejson
.
Thus, the exclusion of all versions of Python will be the same: JSONDecodeError
.
source to share