Python JSON解码报错TypeError : can't use a string pattern on a bytes-like object

标签 python json

<分区>

您好,我正在用 Python 编写代码,试图为一个学校项目制作一个用户友好的货币兑换应用程序,但在尝试解码 json 以获取汇率时遇到了错误。 我使用的代码是:

import urllib.request
import json
(str) = "http://rate-exchange.appspot.com/currency?from=FRM&to=TO&q=AM";
(str) = (str.replace("FRM", "GBP"))
(str) = (str.replace("TO", "USD"))
url = (str.replace("AM", "20"))
f = urllib.request.urlopen(url)
data = (f.read(100))
print (data)
json_input = data
decoded = json.loads(json_input)
print ("conversion is: ", decoded["v"])

我得到的错误是:

b'{"to": "USD", "rate": 1.66215, "from": "GBP", "v": 33.243000000000002}'
Traceback (most recent call last):
File "C:\Users\jay\My Cubby\get qure.py", line 12, in <module>
decoded = json.loads(json_input)
File "C:\Python33\lib\json\__init__.py", line 309, in loads
return _default_decoder.decode(s)
File "C:\Python33\lib\json\decoder.py", line 352, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: can't use a string pattern on a bytes-like object

所以我想知道是否有人对如何修复此错误有任何想法?或者如果有人以前见过这个错误? 在此先感谢您的帮助 J·赖默

最佳答案

在 Python 3 中,您需要将urllib.request.urlopen()bytes 返回值解码 为unicode 字符串:

decoded = json.loads(json_input.decode('utf8'))

这假设您正在使用的 Web 服务使用默认的 JSON 编码 UTF-8。

如果您不想假设,您可以检查字符集的响应:

f = urllib.request.urlopen(url)
charset = f.info().get_param('charset', 'utf8')
data = f.read()
decoded = json.loads(data.decode(charset))

关于Python JSON解码报错TypeError : can't use a string pattern on a bytes-like object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22359997/

相关文章:

javascript - 使用 JSON 填充 header 数据但收到错误 "Cannot read property appendChild of undefined"

python - 大 TSV 文件中 moSTLy 整数字符串列的 pandas read_csv dtype 推断不一致

java - 较短的代码是否会影响解释语言的性能?

python - 使用 Seaborn 或 Matplotlib 的语义差异图

javascript - 如何在 javascript 中从 json 中获取行或单元格?

java - 无法在 struts2 中获取 JSON Url 参数

python - 对于python中的两个图像的差异未获得正确的减法结果

python - 在 Python 中将换行符写入 csv

java - 如何使用 Ajax 和 Struts2 将表单数据发送到 ActionSupport

javascript - 为 AJAX JSON 调用创建 for-loop/.each 循环