2015-11-22 42 views
0

即使在使用decode('utf-8')后,我也会得到低于错误的错误。解码UTF-8后,我得到TypeError:JSON对象必须是str,而不是'bytes'

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) 
+0

使用'response'的两行是相互独立的;哪一个会引发错误?你可能只是想把'response.json()'的返回值赋给某个​​东西,替换一个或两个当前行。 – chepner

+0

'obj = json.load(response)'正在使用该错误。我也注意到我把print obj和str_response都解码了,但是它没有帮助解决这个错误。我试过你的方式,但也许我做的事情不对 – Trm

回答

0

你很近 - 你需要在json.load之前进行解码。即

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) 

您的代码假设网络服务器正在返回“utf-8”编码数据。您应该检查响应中的Content-type标题并适当地设置解码。或者,使用内置自动解码的Requests库。它也解码为JSON,这应该会对你有所帮助。

+0

非常感谢!我还发现我也可以用熊猫阅读它'data = pd.read_json('https://api.myjson.com/bins/33g8e')'。我打算以后再利用它们。 编辑:我试图运行代码,但我得到属性错误:'AttributeError:'str'对象没有属性'read'' – Trm

相关问题