2015-09-26 8 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 

コマンドラインからスクリプトを実行しているとき、私は取得していますエラーは「はTypeError:JSONオブジェクトは、strをしなければならない、ではない 『バイト』」です。私はPythonの初心者ですので、非常に簡単な解決策があります。ここで何か助けてくれてありがとう。

答えて

11

デコードを忘れることとは別に、は、の1度だけ読み取ることができます。すでに.read()が呼び出されている場合、2番目の呼び出しは空の文字列を返します。文字列に一度だけ

コール.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

おかげでたくさんは、今うまく機能します! –

関連する問題