使用query(url请求)将Json放入python变量

2024-04-24 18:54:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图在Python3中使用来自WeatherUnderground的API页面的Python2代码片段。你知道吗

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


Tags: 代码importapijsonstringlocationurllib2urllib
1条回答
网友
1楼 · 发布于 2024-04-24 18:54:47

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

相关问题 更多 >