0

I'm attempting to use this Python 2 code snippet from the WeatherUnderground's API Page in python 3.

import urllib2
import json
f = urllib2.urlopen('http://api.wunderground.com/api/apikey/geolookup/conditions/q/IA/Cedar_Rapids.json')
json_string = f.read()
parsed_json = json.loads(json_string)
location = parsed_json['location']['city']
temp_f = parsed_json['current_observation']['temp_f']
print "Current temperature in %s is: %s" % (location, temp_f)
f.close()

I've used 2to3 to convert it over but i'm still having some issues. The main conversion here is switching from the old urllib2 to the new urllib. I've tried using the requests library to no avail.

Using urllib from python 3 this is the code I have come up with:

import urllib.request
import urllib.error
import urllib.parse
import codecs
import json

url = 'http://api.wunderground.com/api/apikey/forecast/conditions/q/C$
response = urllib.request.urlopen(url)
#Decoding on the two lines below this
reader = codecs.getreader("utf-8")
obj = json.load(reader(response))
json_string = obj.read()
parsed_json = json.loads(json_string)
currentTemp = parsed_json['current_observation']['temp_f']
todayTempLow = parsed_json['forecast']['simpleforecast']['forecastday']['low'][$
todayTempHigh = parsed_json['forecast']['simpleforecast']['forecastday']['high'$
todayPop = parsed_json['forecast']['simpleforecast']['forecastday']['pop']

Yet i'm getting an error about it being the wrong object type. (Bytes instead of str) The closest thing I could find to the solution is this question here.

Let me know if any additional information is needed to help me find a solution!

Heres a link to the WU API website if that helps

Cyclicz
  • 37
  • 1
  • 5

1 Answers1

1

urllib returns a byte array. You convert it to string using

json_string.decode('utf-8')

Your Python2 code would convert to

from urllib import request
import json

f = request.urlopen('http://api.wunderground.com/api/apikey/geolookup/conditions/q/IA/Cedar_Rapids.json')
json_string = f.read()
parsed_json = json.loads(json_string.decode('utf-8'))
location = parsed_json['location']['city']
temp_f = parsed_json['current_observation']['temp_f']
print ("Current temperature in %s is: %s" % (location, temp_f))
f.close()
Andrei Cioara
  • 3,404
  • 5
  • 34
  • 62