频道栏目
首页 > 资讯 > JavaScript > 正文

json数据解析(代码)

18-02-02        来源:[db:作者]  
收藏   我要投稿

json数据解析(代码)

# coding:utf-8

'http://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 = 'http://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)


相关TAG标签
上一篇:数组作为函数的参数怎么传递的?二维数组怎么用指针表示?
下一篇:调用微信公众平台的分享接口,自己分享的只有自己能看见图片别人却看不见是为什么?
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站