Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 解码utf-8后,我得到TypeError:JSON对象必须是str,而不是“bytes”_Python_Json_Utf 8 - Fatal编程技术网

Python 解码utf-8后,我得到TypeError:JSON对象必须是str,而不是“bytes”

Python 解码utf-8后,我得到TypeError:JSON对象必须是str,而不是“bytes”,python,json,utf-8,Python,Json,Utf 8,即使在使用解码“utf-8”后,我也会得到以下错误 TypeError: the JSON object must be str, not 'bytes' 现在我已经读到,在3.x中,很少有人面临类似的问题,但大多数人都是通过使用解码功能来解决的,这对我来说似乎不起作用。谁能帮我一下吗?我是Python的初学者 import urllib.request import json request = 'https://api.myjson.com/bins/56els' response =

即使在使用解码“utf-8”后,我也会得到以下错误

TypeError: the JSON object must be str, not 'bytes'
现在我已经读到,在3.x中,很少有人面临类似的问题,但大多数人都是通过使用解码功能来解决的,这对我来说似乎不起作用。谁能帮我一下吗?我是Python的初学者

import urllib.request
import json

request = 'https://api.myjson.com/bins/56els'
response = urllib.request.urlopen(request)
obj = json.load(response)
str_response = response.readall().decode('utf-8')

print(obj)

很接近了-您需要将解码放在json.load之前。即


代码假定Web服务器返回utf-8编码数据。您应该检查响应上的内容类型标题,并适当地设置解码。或者,使用内置自动解码的请求库。它还可以解码为JSON,这将进一步帮助您。

使用response的两行代码彼此独立;哪一个会引起错误?您可能只想将response.json的返回值分配给某个对象,替换当前行中的一行或两行。obj=json.loadresponse正在使用错误。我还注意到我放了print obj,而不是str_响应,它被解码了,但这对错误没有帮助。我试过你的方法,但也许我做了一些不对的事。谢谢!我还发现我可以用pandas too data=pd.read_json'https://api.myjson.com/bins/33g8e'. 我计划以后使用它们。编辑:我试图运行代码,但得到属性错误:AttributeError:“str”对象没有属性“read”
import urllib.request
import json

request = 'https://api.myjson.com/bins/56els'
response = urllib.request.urlopen(request)
str_response = response.readall().decode('utf-8')
obj = json.load(str_response)

print(obj)