【问题标题】:After decode utf-8 I get TypeError: the JSON object must be str, not 'bytes'解码 utf-8 后我得到 TypeError: the JSON object must be str, not 'bytes'
【发布时间】: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 解码的,但它对错误没有帮助。我试过你的方法,但也许我做的不对

标签: python json utf-8


【解决方案1】:

您已经接近了 - 您需要将解码放在 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,这将进​​一步帮助您。

【讨论】:

  • 非常感谢!我还发现我也可以用 pandas 阅读它data = pd.read_json('https://api.myjson.com/bins/33g8e')。我计划稍后使用它们。编辑:我尝试运行代码,但出现属性错误:AttributeError: 'str' object has no attribute 'read'
猜你喜欢
  • 2012-12-04
  • 2014-03-08
  • 1970-01-01
  • 2019-05-10
  • 2018-09-27
  • 2020-05-29
  • 1970-01-01
相关资源
最近更新 更多