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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With