Python 类型错误:不能在类似字节的对象上使用字符串模式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21436163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:50:52  来源:igfitidea点击:

TypeError: can't use a string pattern on a bytes-like object

pythonjsonstringpython-3.xbytestring

提问by user3249433

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))

Gives this error:

给出这个错误:

TypeError: can't use a string pattern on a bytes-like object

While viewing through the browser i do see that the response is a Json but request library says its a bytes like object why so ?

通过浏览器查看时,我确实看到响应是一个 Json,但请求库说它是一个类似字节的对象,为什么会这样?

采纳答案by falsetru

If you use Python 3.x, you should pass strobject to json.loads.

如果您使用 Python 3.x,您应该将str对象传递给json.loads.

Replace following line:

替换以下行:

print(json.loads(line))

with:

和:

print(json.loads(line.decode()))

UPDATE: The behavior changed in Python 3.6. The argument can now be of type bytes or bytearray. The input encoding should be UTF-8, UTF-16 or UTF-32.

更新:Python 3.6 中的行为发生了变化。参数现在可以是 bytes 或 bytearray 类型。输入编码应为 UTF-8、UTF-16 或 UTF-32。