1 2 3 4 5 6 7 8 9 10 | json_url = 'https://raw.githubusercontent.com/muxuezi/btc/master/btc_close_2017.json' response = urlopen(json_url) # 读取数据 req = response.read() # 将数据写入文件 with open('btc_close_2017_urlib.json', 'wb') as f: f.write(req) # 加载json格式 file_urllib = json.loads(req) print(file_urllib) |
报错:TypeError: the JSON object must be str, not 'bytes’
解决方法:
1 2 | # 加载json格式 file_urllib = json.loads(req.decode('utf-8')) |
原因分析:
报错翻译过来就是翻译过来就是json对象必须是字符串类型,不是字节类型,你需要转换bytes类型。
从网页获取的是json文件,req = response.read()得到的是字节流文件。由 于网站设置的编码模式(encding)是utf-8模式,所以我们要解码decode,req.decode(‘utf-8’)的作用是,将utf-8码字节流类型转化为Unicode类型。
在Python中字符串str是采用Unicode编码的,所以解决这个报错。
我的环境是python3.5, python 3.6 之后,支持直接输入二进制 bytes,不再存在此类错误。
关于encode(),decode()的介绍参见:
https://blog.csdn.net/a921800467b/article/details/8579510