import json
import requests
url = 'http://developer.usa.gov/1usagov.json'
r = requests.get(url, stream=True)
for line in r.iter_lines():
if line:
print (json.loads(line))
给出这个错误:
TypeError: can't use a string pattern on a bytes-like object
通过浏览器查看时,我确实看到响应是一个 Json,但请求库说它是一个字节,比如对象,为什么会这样?
最佳答案
如果您使用 Python 3.x,您应该将 str
对象传递给 json.loads
.
替换以下行:
print(json.loads(line))
与:
print(json.loads(line.decode()))
更新:Python 3.6 中的行为发生了变化。参数现在可以是字节或字节数组类型。输入编码应为 UTF-8、UTF-16 或 UTF-32。
关于python - 类型错误 : can't use a string pattern on a bytes-like object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21436163/