使用 query(url request)将 Json 放入 python 变量中



我正在尝试在python 3中使用WeatherUnderground的API页面中的Python 2代码片段。

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()

我已经使用 2to3 将其转换过来,但我仍然遇到一些问题。这里的主要转换是从旧的urllib2切换到新的urllib。我尝试使用请求库无济于事。

使用 python 3 中的 urllib,这是我想出的代码:

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']

然而,我收到一个错误,说它是错误的对象类型。(字节而不是 str(我能找到的最接近解决方案的是这里的这个问题。

如果需要任何其他信息来帮助我找到解决方案,请告诉我!

这里有一个指向WU API网站的链接,如果有帮助的话

urllib 返回一个字节数组。您可以使用将其转换为字符串

json_string.decode('utf-8')

您的 Python2 代码将转换为

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()

最新更新