【发布时间】:2015-11-22 16:22:18
【问题描述】:
即使在使用 decode('utf-8') 之后,我也会遇到以下错误。
TypeError: the JSON object must be str, not 'bytes'
现在我读到很少有人在 3.x 中遇到过类似的问题,但他们中的大多数人通过使用 decode 函数来解决它,这似乎对我不起作用。任何人都可以帮我解决这个问题吗?我是 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)
【问题讨论】:
-
使用
response的两行是相互独立的;哪一个引发了错误?您可能只想将response.json()的返回值分配给某物,替换当前行中的一个或两个。 -
obj = json.load(response)正在使用该错误。我还注意到我放了 print obj 而不是 str_response 解码的,但它对错误没有帮助。我试过你的方法,但也许我做的不对