json数据解析(代码)
程序员文章站
2022-07-23 20:15:44
json数据解析(代码)
# coding:utf-8
'https://api.map.baidu.com/telematics/v3/weather?loc...
json数据解析(代码)
# coding:utf-8 'https://api.map.baidu.com/telematics/v3/weather?location=郑州市&output=json&ak=TueGDhCvwI6fOrQnLM0qmXxY9N0OkOiQ&callback=?' # 在python中发送请求 # 下载requests包,使用requests发请求 # windows+r 输入cmd 回车打开命令行工具 输入pip install requests # 输入pip list 查看已经安装过的包 import requests # python内置的包,json import json while True: print '**************欢迎使用天气查询系统*****************' # 输入一个要查询的城市名称 city = raw_input('请输入要查询的城市名称(输入q退出):') if city == 'q': break # 1.准备url地址 url = 'https://api.map.baidu.com/telematics/v3/weather?location=%s&output=json&ak=TueGDhCvwI6fOrQnLM0qmXxY9N0OkOiQ&callback=?'%city # 2.发送一个get请求,获取url地址下的资源内容 # get(url) 需要将url地址作为参数进行传递 # response 接受服务器返回的响应数据 response = requests.get(url) # 把json字符串转换python中的字典或列表 weather_dict = json.loads(response.content) # 根据key取出字典中对应的值 date = weather_dict.get('date') # 取出results列表 results = weather_dict['results'] # 取出results中的字典 detail_dict = results[0] # 取出当前城市 current_city = detail_dict['currentCity'] print u'当前城市:%s' % current_city # 取出pm值 pm25 = detail_dict['pm25'] # 把取出的pm25字符串转换为数字,再进行比较 pm25 = int(pm25) if pm25 <= 50: print 'pm值%s,优' % pm25 elif pm25 <= 100: print 'pm值%s,良' % pm25 elif pm25 <= 150: print 'pm值%s,轻度污染' % pm25 elif pm25 <= 200: print 'pm值%s,中度污染' % pm25 elif pm25 <= 300: print 'pm值%s,重度污染' % pm25 else: print 'pm值%s,严重污染' % pm25 # 取出指引列表 indexs = detail_dict['index'] # for循环遍历index列表,取出小字典 for index in indexs: title = index['title'] zs = index['zs'] tipt = index['tipt'] des = index['des'] print u'标题:%s 指数:%s 提示:%s 建议:%s'%(title,zs,tipt,des) # 取出天气情况列表 weather_data = detail_dict['weather_data'] # for循环遍历weather_data,取出小字典 for weather_dict in weather_data: date = weather_dict['date'] weather = weather_dict['weather'] wind = weather_dict['wind'] temperature = weather_dict['temperature'] print u'日期:%s 天气:%s 风级:%s 温度:%s'%(date,weather,wind,temperature)
上一篇: 防止SQL注入
下一篇: 华为云云手机亮相全球互联网技术大会