如何解决如何使用 urllib3 在 Python 中直接从 github 读取这个 json 文件?
我正在尝试从 github 导入一个特定的 json 文件
import urllib3
import json
http = urllib3.PoolManager()
url = 'https://raw.githubusercontent.com/leanhdung1994/BigData/main/fr-esr-principaux-etablissements-enseignement-superieur.json'
f = http.request('GET',url)
data = json.load(f.data)
能否请您解释一下为什么会出现以下错误以及如何正确读取此文件?
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-14-cc9b55b171d7> in <module>
4 url = 'https://raw.githubusercontent.com/leanhdung1994/BigData/main/fr-esr-principaux-etablissements-enseignement-superieur.json'
5 f = http.request('GET',url)
----> 6 data = json.load(f.data)
~\anaconda3\lib\json\__init__.py in load(fp,cls,object_hook,parse_float,parse_int,parse_constant,object_pairs_hook,**kw)
291 kwarg; otherwise ``JSONDecoder`` is used.
292 """
--> 293 return loads(fp.read(),294 cls=cls,object_hook=object_hook,295 parse_float=parse_float,parse_int=parse_int,AttributeError: 'bytes' object has no attribute 'read'
解决方法
我建议使用更现代的 urllib3
库,而不是使用 requests
。
您的代码可能如下所示:
import requests
url = 'https://raw.githubusercontent.com/leanhdung1994/BigData/main/fr-esr-principaux-etablissements-enseignement-superieur.json'
f = requests.get(url)
# The .json() method automatically parses the response into JSON.
data = f.json()
如果要使用urllib3,必须对数据进行解码,使用json加载(不是load)方法。例如:
import urllib3
import json
http = urllib3.PoolManager()
url = 'https://raw.githubusercontent.com/leanhdung1994/BigData/main/fr-esr-principaux-etablissements-enseignement-superieur.json'
f = http.request('GET',url)
data = json.loads(f.data.decode("utf8"))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。