没有返回任何内容时处理JSON解码错误 [英] Handle JSON Decode Error when nothing returned
问题描述
我正在解析json数据.我的解析没有问题,我正在使用simplejson
模块.但是某些api请求返回空值.这是我的示例:
I am parsing json data. I don't have an issue with parsing and I am using simplejson
module. But some api requests returns empty value. Here is my example:
{
"all" : {
"count" : 0,
"questions" : [ ]
}
}
这是我解析json对象的代码段:
This is the segment of my code where I parse the json object:
qByUser = byUsrUrlObj.read()
qUserData = json.loads(qByUser).decode('utf-8')
questionSubjs = qUserData["all"]["questions"]
正如我对某些请求所提到的,出现以下错误:
As I mentioned for some requests I get the following error:
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)
处理此错误的最佳方法是什么?
What would be the best way to handle this error?
推荐答案
Python编程中有一个规则,即宽恕比许可容易"(简称EAFP).这意味着您应该捕获异常,而不是检查值的有效性.
There is a rule in Python programming called "it is Easier to Ask for Forgiveness than for Permission" (in short: EAFP). It means that you should catch exceptions instead of checking values for validity.
因此,请尝试以下操作:
Thus, try the following:
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'
编辑:由于simplejson.decoder.JSONDecodeError
实际上是从ValueError
继承的(
EDIT: Since simplejson.decoder.JSONDecodeError
actually inherits from ValueError
(proof here), I simplified the catch statement by just using ValueError
.
这篇关于没有返回任何内容时处理JSON解码错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!