Python JSON解码错误TypeError:不能在类似字节的对象上使用字符串模式 [英] Python JSON decoding error TypeError: can't use a string pattern on a bytes-like object
问题描述
您好,我正在用python编写代码,试图为学校项目制作一个用户友好的货币兑换应用程序,但是在尝试解码汇率的json时遇到了错误. 我正在使用的代码是:
Hi there i am coding in python trying to make a user friendly currency exchange app for a school project but have encountered and error with trying to decode json for the exchange rates. The code i'm using is:
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.Rymer)
So i was just wondering if anyone had any ideas of how to fix this error? Or if anyone has seen this error before? Thanks in advance for any help J.Rymer
推荐答案
在Python 3中,您需要 decode 将bytes
返回值从urllib.request.urlopen()
转换为unicode字符串:
In Python 3, you need to decode the bytes
return value from urllib.request.urlopen()
to a unicode string:
decoded = json.loads(json_input.decode('utf8'))
这假定您正在使用的Web服务正在使用UTF-8的默认JSON编码.
This makes the assumption that the web service you are using is using the default JSON encoding of UTF-8.
如果不想使用以下字符,则可以检查字符集的响应:
You could check the response for a character set if you don't want to assume:
f = urllib.request.urlopen(url)
charset = f.info().get_param('charset', 'utf8')
data = f.read()
decoded = json.loads(data.decode(charset))
这篇关于Python JSON解码错误TypeError:不能在类似字节的对象上使用字符串模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!