JSONDecodeError:期望值:第1行第1列

bee*_*eny 17 json python-3.x

我在Python 3.5.1中收到此错误.

json.decoder.JSONDecodeError:期望值:第1行第1列(char 0)

这是我的代码:

import json
import urllib.request

connection = urllib.request.urlopen('http://python-data.dr-chuck.net/comments_220996.json')

js = connection.read()

print(js)

info = json.loads(str(js))
Run Code Online (Sandbox Code Playgroud)

图片

Dan*_*owe 21

如果你查看你收到的输出print()以及你的Traceback,你会看到你得到的值不是字符串,它是一个字节对象(前缀为b):

b'{\n  "note":"This file    .....
Run Code Online (Sandbox Code Playgroud)

如果您使用诸如此类的工具获取URL curl -v,您将看到内容类型为

Content-Type: application/json; charset=utf-8
Run Code Online (Sandbox Code Playgroud)

所以它是JSON,编码为UTF-8,Python正在考虑它是一个字节流,而不是一个简单的字符串.要解析此问题,您需要先将其转换为字符串.

将最后一行代码更改为:

info = json.loads(js.decode("utf-8"))
Run Code Online (Sandbox Code Playgroud)

  • 我正在做 json.loads(js.decode("utf-8")) 但它给出了一个错误 AttributeError: 'str' object has no attribute 'decode' (2认同)
  • @AnwarHussain 那么你的 JSON 数据(在 `js` 中)已经是一个字符串(`str`)并且不需要解码。您可以将它直接传递给 `json.loads()` 而无需 decode 函数。`json.loads(js)`。 (2认同)