python - 无返回时处理 JSON 解码错误

标签 python json python-3.x

我正在解析 json 数据。我没有解析问题,我正在使用 simplejson 模块。但是一些 api 请求返回空值。这是我的例子:

{
"all" : {
    "count" : 0,
    "questions" : [     ]
    }
}

这是我解析 json 对象的代码段:

 qByUser = byUsrUrlObj.read()
 qUserData = json.loads(qByUser).decode('utf-8')
 questionSubjs = qUserData["all"]["questions"]

正如我提到的一些请求,我收到以下错误:

Traceback (most recent call last):
  File "YahooQueryData.py", line 164, in <module>
    qUserData = json.loads(qByUser)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/simplejson/__init__.py", line 385, in loads
    return _default_decoder.decode(s)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/simplejson/decoder.py", line 402, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/simplejson/decoder.py", line 420, in raw_decode
    raise JSONDecodeError("No JSON object could be decoded", s, idx)
simplejson.decoder.JSONDecodeError: No JSON object could be decoded: line 1 column 0 (char 0)

处理此错误的最佳方法是什么?

最佳答案

Python 编程中有一条规则叫做“请求宽恕比请求许可更容易”(简称:EAFP)。这意味着您应该捕获异常而不是检查值的有效性。

因此,请尝试以下操作:

try:
    qByUser = byUsrUrlObj.read()
    qUserData = json.loads(qByUser).decode('utf-8')
    questionSubjs = qUserData["all"]["questions"]
except ValueError:  # includes simplejson.decoder.JSONDecodeError
    print('Decoding JSON has failed')

EDIT:由于 simplejson.decoder.JSONDecodeError 实际上继承自 ValueError ( proof here ),所以我只使用简单的 catch 语句ValueError.

关于python - 无返回时处理 JSON 解码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8381193/

相关文章:

python - 添加相对路径到配置文件virtualenv_path_extensions.pth

python - 高效快速地搜索字典中的字典的方法

ios - Meteor 网络应用程序可以向 iOS 应用程序提供数据吗?

java - 将 JSONObject/JSONArray 转换为字符串数组时出现问题

python - 如何在 python 中使用正则表达式在特定单词之前获取特定模式的所有日期或关键字?

c++ - cython - 分配 C++ 类实例指针时出现段错误

python - 从带有行和列标题的 csv 文件中读取 networkx 图

ios - 在iOS应用程序中解析JSON数据返回空数组

python - 在python3.2中等待一段时间再执行下一段代码

Python 内存释放