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

时间:2017-05-23 02:17:06

标签: python json

我试图在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) 我能找到最接近解决方案的问题是here.

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

Heres a link to the WU API website if that helps

1 个答案:

答案 0 :(得分:1)

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