Issue
I wrote the following code that works with python3
try:
json.loads(text)
except json.decoder.JSONDecodeError:
(exception handling)
However, if I use python2, when json.loads
throws the exception I get:
File "mycode.py", line xxx, in function
except json.decoder.JSONDecodeError:
AttributeError: 'module' object has no attribute 'JSONDecodeError'
And actually, https://docs.python.org/2/library/json.html doesn't mention any JSONDecodeError exception, while https://docs.python.org/3/library/json.html does.
How can I have the code running both with python 2 and 3?
Solution
In Python 2 json.loads
raises ValueError
:
Python 2.7.9 (default, Sep 17 2016, 20:26:04)
>>> json.loads('#$')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
You can try to use json.decoder.JSONDecodeError
. If it fails you will know that you need to catch ValueError
:
try:
json_parse_exception = json.decoder.JSONDecodeError
except AttributeError: # Python 2
json_parse_exception = ValueError
Then
try:
json.loads(text)
except json_parse_exception:
(exception handling)
Will work in either case.
Answered By - DeepSpace
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.