您的位置:首页 > 编程语言 > Python开发

Python语言基础--6(json解析)

2018-01-23 11:12 459 查看
#python 2.7
#coding:utf-8

#url 统一资源定位符
#在python中发送请求
#下载requests包,用其发送请求
#windows+r cmd 输入 pip install requests

import requests
import json
#1.准备url地址
while 1:
l=raw_input('请输入要查询城市:')
url='http://api.map.baidu.com/telematics/v3/weather?location={}&output=json&ak=TueGDhCvwI6fOrQnLM0qmXxY9N0OkOiQ&callback=?'.format(l)
#url= 'http://api.map.baidu.com/telematics/v3/weather?location=%s&output=json&ak=TueGDhCvwI6fOrQnLM0qmXxY9N0OkOiQ&callback=?'%l
#2.发送一个get请求,获取url地址下的资源内容
#get(url)
# response 接收服务器返回的响应数据
response=requests.get(url)
#print response.content
#将json中的字符串转换为python中的字典或列表
weather_dict=json.loads(response.content)
#print type(weather_dict)
#根据key取出字典中对应值
date=weather_dict.get('date')
#print date
#取出 results列表
results=weather_dict['results']
#取出results中字典
detail_dict=results[0]
current_city=detail_dict['currentCity']
print '当前城市:',current_city
pm25=int(detail_dict['pm25'])
if 0<=pm25<=50:
print 'PM2.5:',pm25,'优'
elif pm25<=100:
print 'PM2.5:', pm25, '良'
elif pm25<=150:
print 'PM2.5:', pm25, '轻度污染'
elif pm25<=200:
print 'PM2.5:', pm25, '中度污染'
elif pm25<=300:
print 'PM2.5:', pm25, '重度污染'
else:
print 'PM2.5:', pm25, '严重污染'
#取出index列表
detail_index=detail_dict['index']
#取出index列表中第一个字典
for i in range(0,5):
detail_index_dict=detail_index[i]
#取出字典中相应内容
print '********************'
print detail_index_dict['title'],detail_index_dict['zs']
print '********************'
print detail_index_dict['tipt'],detail_index_dict['des']
detail_weather_data=detail_dict['weather_data']
for j in range(0,4):
detail_weather_data_dict=detail_weather_data[j]
print '********************'
print detail_weather_data_dict['date'],detail_weather_data_dict['weather'],detail_weather_data_dict['wind']
print detail_weather_data_dict['temperature']
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息