python - JSON 错误 : "end is out of bounds"?

标签 python json

我遇到了一个我无法理解的问题。我通过 Redis(作为队列)将 json 数据作为字符串发送,接收方抛出以下错误:

[ERROR JSON (in queue)] - {"ip": null, "domain": "somedomain.com", "name": "Some user name", "contact_id": 12345, "signature": 
"6f496a4eaba2c1ea4e371ea2c4951ad92f41ddf45ff4949ffa761b0648a22e38"} => end is out of bounds

抛出异常的代码如下:

try:
    item = json.loads(item[1])
except ValueError as e:
    sys.stderr.write("[ERROR JSON (in queue)] - {1} => {0}\n".format(str(e), str(item)))
    return None

真正奇怪的是,如果我打开 python 控制台并执行以下操作:

>>> import json
>>> s = '{"ip": null, "domain": "somedomain.com", "name": "Some user name", "contact_id": 12345, "signature": "6f496a4eaba2c1ea4e371ea2c4951ad92f41ddf45ff4949ffa761b0648a22e38"}'
>>> print s

我没有问题,字符串(在 Python 控制台中复制/粘贴)完全没有产生错误,但我的原始代码抛出了一个错误!

您知道导致问题的原因吗?

最佳答案

您正在加载 item[1],它是字符串 items 的第二个字符:

>>> json.loads('"')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 365, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 381, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: end is out of bounds

你应该写:

item = json.loads(item)

关于python - JSON 错误 : "end is out of bounds"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37445874/

相关文章:

python - 有没有一种简单的方法可以对 pandas 数据框中的分布进行所有成对统计比较?

python - Pandas 日期时间 : Aggregate based on time lag

c# - 当单个对象属性是字符串时,如何防止将其转换为 DateTime

java - 我尝试使用 Retrofit 将 JSON 解析为 Java

ios - 在 TableView 单元格中通过alamofire解析json数据

javascript - 在 textarea 输入中美化 json 数据

python - 如何在 Python 中将数据从字典写入 CSV 文件

python - 更好/更快地循环遍历集合或列表?

python - xmpppy 连接到 gtalk 时出错

javascript - 直接访问 JSON 子对象的更好方法