2014-03-12 34 views
2

嗨,我在Python編碼嘗試做一個學校項目的用戶友好的貨幣兌換應用程序,但遇到並嘗試解碼json的匯率。 我使用的代碼是:Python的JSON解碼錯誤TypeError:不能在類似字節的對象上使用字符串模式

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

回答

10

在Python 3,您需要解碼urllib.request.urlopen() Unicode字符串的bytes返回值:

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

這使得假設網您正在使用的服務正在使用UTF-8的默認JSON編碼。

您可以檢查設置的字符的響應,如果你不想承擔:

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

感謝您的快速性反應!它工作100%,所以謝謝:) – jjr2000

+0

再次感謝我接受了你。 ;) – jjr2000

+0

在'django-rest-framework'測試中,第一個已解碼的代碼片段適用於我。謝謝 –

相關問題