我编写了以下与python3一起工作的代码
try:
json.loads(text)
except json.decoder.JSONDecodeError:
(exception handling)
但是,如果我使用python2,当json.loads
抛出异常时,会得到:
File "mycode.py", line xxx, in function
except json.decoder.JSONDecodeError:
AttributeError: 'module' object has no attribute 'JSONDecodeError'
实际上,https://docs.python.org/2/library/json.html没有提到任何JSONDecodeError异常,而https://docs.python.org/3/library/json.html却提到了。
如何使用python 2和3同时运行代码?
发布于 2018-11-17 20:53:18
在Python2中,json.loads
引发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
您可以尝试使用json.decoder.JSONDecodeError
。如果它失败了,您将知道需要捕获ValueError
try:
json_parse_exception = json.decoder.JSONDecodeError
except AttributeError: # Python 2
json_parse_exception = ValueError
然后
try:
json.loads(text)
except json_parse_exception:
(exception handling)
在这两种情况下都能起作用。
https://stackoverflow.com/questions/53355389
复制相似问题