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

时间:2023-01-28 20:13:47
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,但是请求库说它的字节像对象一样,为什么呢?

1 个解决方案

#1


37  

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

如果您使用Python 3。应该将str对象传递给json.load。

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中的行为发生了变化。参数现在可以是字节类型或bytearray类型。输入编码应该是UTF-8、UTF-16或UTF-32。

#1


37  

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

如果您使用Python 3。应该将str对象传递给json.load。

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中的行为发生了变化。参数现在可以是字节类型或bytearray类型。输入编码应该是UTF-8、UTF-16或UTF-32。