【发布时间】:2015-09-18 18:49:32
【问题描述】:
我一直在使用几个 Web API,但这个让我感到困惑。我不知道我出了什么问题。
此代码适用于一个 api,但不适用于这个。
response = urllib.request.urlopen(self.query_base)
reader = codecs.getreader("utf-8")
obj = json.load(reader(response))
return obj
这给了我以下错误
UnicodeEncodeError: 'charmap' codec can't encode character '\U0001f602' in position 4096: character maps to <undefined>
我试过了:
response = urllib.request.urlopen(self.query_base)
obj = json.load(response.decode("utf-8"))
return obj
给出:
AttributeError: 'HTTPResponse' object has no attribute 'decode'
和,
response = urllib.request.urlopen(self.query_base).read()
obj = json.load(response)
return obj
给了
AttributeError: 'bytes' object has no attribute 'read'
和,
response = urllib.request.urlopen(self.query_base)
obj = json.load(response)
给了
TypeError: the JSON object must be str, not 'bytes'
以及我在此处的其他类似主题中发现的任何其他组合
我不记得以前遇到过这个问题,我确定我错过了一些东西,但我看不到什么。
【问题讨论】:
-
有一点需要注意,当 urllib 在 https URI 上遇到“无效”的 ssl 证书时往往会遇到困难。如果没有正确的标志,它会默默地失败。
-
你确定你从你发布的代码中得到了
UnicodeEncodeError吗?我希望UnicodeDecodeError例外。请为您的错误发布完整回溯,但我很确定您的代码有效,但您尝试打印结果。 -
^ 好点,我会调查的。虽然如果我用浏览器打开 url,它会下载 json 文件并毫无问题地打开它。
-
@MartijnPieters 啊,不错,这个错误实际上来自下一个函数中的打印语句(仅用于在我写作时进行测试)我想我必须先对它做些什么才能显示数据?
标签: python json python-3.x