use*_*433 25 python string json bytestring python-3.x
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))
Run Code Online (Sandbox Code Playgroud)
给出了这个错误:
TypeError: can't use a string pattern on a bytes-like object
Run Code Online (Sandbox Code Playgroud)
通过浏览器查看时,我确实看到响应是一个Json,但请求库说它像对象一样的字节为什么呢?
fal*_*tru 37
如果您使用Python 3.x,则应将str对象传递给json.loads.
替换以下行:
print(json.loads(line))
Run Code Online (Sandbox Code Playgroud)
有:
print(json.loads(line.decode()))
Run Code Online (Sandbox Code Playgroud)
更新:Python 3.6中的行为已更改.参数现在可以是bytes或bytearray类型.输入编码应为UTF-8,UTF-16或UTF-32.
| 归档时间: |
|
| 查看次数: |
23174 次 |
| 最近记录: |