Python Json错误:ValueError:无法解码JSON对象

时间:2015-06-17 03:30:48

标签: python json

我执行此脚本时遇到错误但无法解决。

错误:

Traceback (most recent call last):
  File "./upload.py", line 227, in <module>
    postImage()
  File "./upload.py", line 152, in postImage
    reddit = RedditConnection(redditUsername, redditPassword)
  File "./upload.py", line 68, in __init__
    self.modhash = r.json()['json']['data']['modhash']
  File "/usr/lib/python2.6/site-packages/requests/models.py", line 799, in json
    return json.loads(self.text, **kwargs)
  File "/usr/lib/python2.6/site-packages/simplejson/__init__.py", line 307, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.6/site-packages/simplejson/decoder.py", line 335, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.6/site-packages/simplejson/decoder.py", line 353, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

1 个答案:

答案 0 :(得分:5)

您收到此异常是因为您在此处使用了错误的json函数:

def getNumberOfFailures(path):
try:
    with open(path + '.failurecount') as f:
        return json.loads(f.read())
except:
    return 0

你需要这样做:

def getNumberOfFailures(path):
    try:
        with open(path + '.failurecount') as f:
            return json.load(f)
    except:
        return 0

json.loads()用于json字符串。 json.load()用于json文件对象。

正如有些人提到的那样,您需要重新发布一个新的API密钥并删除您在代码中发布的密钥。其他人可以并且会滥用这些密钥以您的名义发送垃圾邮件Reddit。