【发布时间】:2018-11-17 20:42:49
【问题描述】:
我编写了以下与 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 上?
【问题讨论】:
-
在 2.x 文档中,它指的是
ValueError,其中 3.x 指的是JSONDecodeError。
标签: python-3.x python-2.x