2015-09-26 35 views
5

我在使用模塊'json'和'urllib.request'在一個簡單的Python腳本測試中一起工作時遇到問題。使用Python 3.5,這裏是代碼:使用urllib.request和json模塊在Python中加載JSON對象

import json 
import urllib.request 

urlData = "http://api.openweathermap.org/data/2.5/weather?q=Boras,SE" 
webURL = urllib.request.urlopen(urlData) 
print(webURL.read()) 
JSON_object = json.loads(webURL.read()) #this is the line that doesn't work 

運行時通過命令行腳本,我得到的錯誤是「類型錯誤:JSON對象必須str的,而不是‘字節’」。我是Python新手,所以很可能有一個非常簡單的解決方案。感謝這裏的任何幫助。

回答

11

除了忘記解碼,您只能讀取一次。已經調用.read()後,第二次調用返回一個空字符串。

呼叫.read()只有一次,和解碼的數據轉換爲字符串:

data = webURL.read() 
print(data) 
encoding = webURL.info().get_content_charset('utf-8') 
JSON_object = json.loads(data.decode(encoding)) 

response.info().get_content_charset() call告訴你什麼字符集的服務器認爲被使用。

演示:

>>> import json 
>>> import urllib.request 
>>> urlData = "http://api.openweathermap.org/data/2.5/weather?q=Boras,SE" 
>>> webURL = urllib.request.urlopen(urlData) 
>>> data = webURL.read() 
>>> encoding = webURL.info().get_content_charset('utf-8') 
>>> json.loads(data.decode(encoding)) 
{'coord': {'lat': 57.72, 'lon': 12.94}, 'visibility': 10000, 'name': 'Boras', 'main': {'pressure': 1021, 'humidity': 71, 'temp_min': 285.15, 'temp': 286.39, 'temp_max': 288.15}, 'id': 2720501, 'weather': [{'id': 802, 'description': 'scattered clouds', 'icon': '03d', 'main': 'Clouds'}], 'wind': {'speed': 5.1, 'deg': 260}, 'sys': {'type': 1, 'country': 'SE', 'sunrise': 1443243685, 'id': 5384, 'message': 0.0132, 'sunset': 1443286590}, 'dt': 1443257400, 'cod': 200, 'base': 'stations', 'clouds': {'all': 40}} 
+0

多謝,現在效果很好! –