flask天气预报json数据的读取

def get_weather(query1):
    api_url = "http://www.sojson.com/open/api/weather/json.shtml?city={}"
    # GBK的url编码 将空格等转换
    #query1 = urllib.quote(query1)
    # url = api_url.format() +unicode(query1)
    # 填充{}内容
    url = api_url.format(query1)
    data = urllib2.urlopen(url).read()
    parsed = json.loads(data)
    weather = None
    if parsed.get("data"):
        weather = {
            "description": parsed["data"],
            "city": parsed.get("city"),

        }
    return weather
测试天气预报JSON数据读取,选取了国内的一个天气APi
http://www.sojson.com/open/api/weather/json.shtml?city=北京
最先将传递来的城市urllib.quote(query1)英文原著上将城市中的空格转化成GBK的url编码
结果在调试中get城市数据后有错误,最后没有转化直接带入没什么错误,取得天气数据是一个python字典。如:
 
 
{"date":"20171119","message":"Success !","status":200,"city":"北京","count":44,"data":{"shidu":"34%","pm25":88.0,"pm10":127.0,"quality":"轻度污染","wendu":"-2","ganmao":"儿童、老年人及心脏、呼吸系统疾病患者人群应减少长时间或高强度户外锻炼","yesterday":{"date":"18日星期六","sunrise":"07:01","high":"高温 5.0℃","low":"低温 -6.0℃","sunset":"16:57","aqi":65.0,"fx":"西风","fl":"3-4级","type":"晴","notice":"晴空万里,去沐浴阳光吧"},"forecast":[{"date":"19日星期日","sunrise":"07:02","high":"高温 7.0℃","low":"低温 -5.0℃","sunset":"16:56","aqi":136.0,"fx":"西南风","fl":"<3级","type":"多云","notice":"今日多云,骑上单车去看看世界吧"},{"date":"20日星期一","sunrise":"07:03","high":"高温 10.0℃","low":"低温 -3.0℃","sunset":"16:55","aqi":128.0,"fx":"西南风","fl":"<3级","type":"晴","notice":"lovely sunshine,尽情享受阳光的温暖吧"},{"date":"21日星期二","sunrise":"07:04","high":"高温 8.0℃","low":"低温 -2.0℃","sunset":"16:55","aqi":257.0,"fx":"西风","fl":"<3级","type":"多云","notice":"绵绵的云朵,形状千变万化"},{"date":"22日星期三","sunrise":"07:06","high":"高温 8.0℃","low":"低温 -3.0℃","sunset":"16:54","aqi":65.0,"fx":"西北风","fl":"4-5级","type":"多云","notice":"悠悠的云里有淡淡的诗"},{"date":"23日星期四","sunrise":"07:07","high":"高温 7.0℃","low":"低温 -3.0℃","sunset":"16:54","aqi":89.0,"fx":"西南风","fl":"<3级","type":"晴","notice":"晴空万里,去沐浴阳光吧"}]}}

读取我们所要的数据就是weather[description][shidu]等。当然只是为了检测,没有对error处理。
 

猜你喜欢

转载自blog.csdn.net/lap2004/article/details/78576230
今日推荐