2015-11-22 41 views
0

即使在使用decode('utf-8')後,我也會得到低於錯誤的錯誤。解碼UTF-8後,我得到TypeError:JSON對象必須是str,而不是'bytes'

TypeError: the JSON object must be str, not 'bytes' 

現在我讀過相當多幾個人在面對3.X類似的問題,但他們大多利用解碼功能,這似乎並沒有爲我工作解決這個問題。任何人都可以幫我一下嗎?我是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) 
+0

使用'response'的兩行是相互獨立的;哪一個會引發錯誤?你可能只是想把'response.json()'的返回值賦給某個​​東西,替換一個或兩個當前行。 – chepner

+0

'obj = json.load(response)'正在使用該錯誤。我也注意到我把print obj和str_response都解碼了,但是它沒有幫助解決這個錯誤。我試過你的方式,但也許我做的事情不對 – Trm

回答

0

你很近 - 你需要在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,這應該會對你有所幫助。

+0

非常感謝!我還發現我也可以用熊貓閱讀它'data = pd.read_json('https://api.myjson.com/bins/33g8e')'。我打算以後再利用它們。 編輯:我試圖運行代碼,但我得到屬性錯誤:'AttributeError:'str'對象沒有屬性'read'' – Trm

相關問題