Loading JSON object in Python using urllib.request and json modules -


i having problems making modules 'json' , 'urllib.request' work in simple python script test. using python 3.5 , here code:

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 line doesn't work 

when running script through command line error getting "typeerror:the json object must str, not 'bytes'". new python there easy solution is. appreciate here.

apart forgetting decode, can read response once. having called .read() already, second call returns empty string.

call .read() once, , decode data string:

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

the response.info().get_content_charset() call tells characterset server thinks used.

demo:

>>> 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}} 

Comments