标签:def 字典 end jsonview ice class ati open 1.0
# api aplication programming interface
# 不通软件不同系统之间的功能相互调用
# json是其中重要的一种数据交换形式
# 定制天气预报 https://www.sojson.com/open/api/weather/json.shtml?city=
# http://jsonviewer.stack.hu/
# https://www.sojson.com/open/api/weather/json.shtml
?city=%E5%8C%97%E4%BA%AC
import requests # pip install requests 请求 网上api的调用形式
url = ‘https://www.sojson.com/open/api/weather/json.shtml?city=‘
city = ‘北京‘
ret = requests.get(url + city) # 请求的对象
print(ret.json())
{‘date‘: ‘20180804‘, ‘message‘: ‘Success !‘, ‘status‘: 200, ‘city‘: ‘北京‘, ‘count‘: 9, ‘data‘: {‘shidu‘: ‘70%‘, ‘pm25‘: 44.0, ‘pm10‘: 78.0, ‘quality‘: ‘良‘, ‘wendu‘: ‘30‘, ‘ganmao‘: ‘极少数敏感人群应减少户外活动‘, ‘yesterday‘: {‘date‘: ‘03日星期五‘, ‘sunrise‘: ‘05:13‘, ‘high‘: ‘高温 36.0℃‘, ‘low‘: ‘低温 26.0℃‘, ‘sunset‘: ‘19:27‘, ‘aqi‘: 107.0, ‘fx‘: ‘南风‘, ‘fl‘: ‘<3级‘, ‘type‘: ‘晴‘, ‘notice‘: ‘愿你拥有比阳光明媚的心情‘}, ‘forecast‘: [{‘date‘: ‘04日星期六‘, ‘sunrise‘: ‘05:14‘, ‘high‘: ‘高温 36.0℃‘, ‘low‘: ‘低温 27.0℃‘, ‘sunset‘: ‘19:26‘, ‘aqi‘: 97.0, ‘fx‘: ‘南风‘, ‘fl‘: ‘<3级‘, ‘type‘: ‘晴‘, ‘notice‘: ‘愿你拥有比阳光明媚的心情‘}, {‘date‘: ‘05日星期日‘, ‘sunrise‘: ‘05:15‘, ‘high‘: ‘高温 35.0℃‘, ‘low‘: ‘低温 25.0℃‘, ‘sunset‘: ‘19:25‘, ‘aqi‘: 103.0, ‘fx‘: ‘东南风‘, ‘fl‘: ‘<3级‘, ‘type‘: ‘雷阵雨‘, ‘notice‘: ‘带好雨具,别在树下躲雨‘}, {‘date‘: ‘06日星期一‘, ‘sunrise‘: ‘05:16‘, ‘high‘: ‘高温 31.0℃‘, ‘low‘: ‘低温 25.0℃‘, ‘sunset‘: ‘19:24‘, ‘aqi‘: 97.0, ‘fx‘: ‘南风‘, ‘fl‘: ‘<3级‘, ‘type‘: ‘雷阵雨‘, ‘notice‘: ‘带好雨具,别在树下躲雨‘}, {‘date‘: ‘07日星期二‘, ‘sunrise‘: ‘05:17‘, ‘high‘: ‘高温 31.0℃‘, ‘low‘: ‘低温 25.0℃‘, ‘sunset‘: ‘19:22‘, ‘aqi‘: 113.0, ‘fx‘: ‘西南风‘, ‘fl‘: ‘<3级‘, ‘type‘: ‘雷阵雨‘, ‘notice‘: ‘带好雨具,别在树下躲雨‘}, {‘date‘: ‘08日星期三‘, ‘sunrise‘: ‘05:18‘, ‘high‘: ‘高温 30.0℃‘, ‘low‘: ‘低温 24.0℃‘, ‘sunset‘: ‘19:21‘, ‘aqi‘: 68.0, ‘fx‘: ‘东南风‘, ‘fl‘: ‘<3级‘, ‘type‘: ‘雷阵雨‘, ‘notice‘: ‘带好雨具,别在树下躲雨‘}]}}
# 象字典一样取值
d = ret.json()
# print(d[‘status‘])
# print(d[‘city‘])
# print(d[‘data‘])
# print(d[‘data‘][‘yesterday‘])
def hot_weather(data):
"""定制化天气预报"""
try:
weather_list = data[‘data‘][‘forecast‘]
# print(weather_list)
for day in weather_list:
print(day[‘date‘], day[‘high‘], day[‘low‘], day[‘sunset‘], day[‘notice‘])
except Exception as e:
print(e)
hot_weather(d)
04日星期六 高温 36.0℃ 低温 27.0℃ 19:26 愿你拥有比阳光明媚的心情
05日星期日 高温 35.0℃ 低温 25.0℃ 19:25 带好雨具,别在树下躲雨
06日星期一 高温 31.0℃ 低温 25.0℃ 19:24 带好雨具,别在树下躲雨
07日星期二 高温 31.0℃ 低温 25.0℃ 19:22 带好雨具,别在树下躲雨
08日星期三 高温 30.0℃ 低温 24.0℃ 19:21 带好雨具,别在树下躲雨
%cd D:\全栈\json api
d = ret.json()
import json
with open(‘weather.json‘, ‘w‘) as f:
json.dump(d, f)
D:\全栈\json api
标签:def 字典 end jsonview ice class ati open 1.0
原文地址:http://blog.51cto.com/13118411/2154806