2015-09-26 15 views
5

Ho problemi nel far funzionare insieme i moduli "json" e "urllib.request" in un semplice test di script Python. Utilizzando Python 3.5 e qui è il codice:Caricamento di oggetti JSON in Python utilizzando i moduli urllib.request e 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 

Quando si esegue lo script attraverso la linea di comando l'errore che sto ottenendo è "TypeError: l'oggetto JSON deve essere str, non e 'byte'". Sono nuovo di Python quindi è molto probabile che sia una soluzione molto semplice. Apprezzo qualsiasi aiuto qui.

risposta

11

Oltre a dimenticare la decodifica, è possibile leggere solo la risposta una volta. Avendo già chiamato .read(), la seconda chiamata restituisce una stringa vuota.

chiamata .read() solo una volta, e decodificare i dati in una stringa:

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

Il response.info().get_content_charset() call ti dice quello che CharacterSet il server pensa viene utilizzato.

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

Grazie mille, funziona bene ora! –

Problemi correlati