L2.1.1 dict和json互转,请求天气

python字典和通用结构json 相互转化

import  json
student_list = [
    {'no':1, 'name':'小明', 'age': 13},
    {'no':2, 'name':'小红', 'age': 10},
    {'no':3, 'name':'小李', 'age': 15}
]

student_json = """
{
    "student_list":[{"no":1, "name":"小明", "age": 13},
    {"no":2, "name":"小红", "age": 10},
    {"no":3, "name":"小李", "age": 15}],
    "student_name":"郑州",
    "address":"管城回族区"
}
"""
#对象转json   发信息
stu_json = json.dumps(student_list, indent=4)
print(type(stu_json), stu_json)
"""
json.dumps(数据对象)  返回json格式字符串。
形如\u5c0f是中文的unicode编码。计算机传输的本质是二进制信息。
"""

#json转换成python对象    接收信息
stu_obj = json.loads(student_json)
print(stu_obj)
for stu in stu_obj['student_list']:
    print(f'学生姓名{stu["name"]}')
# 学生姓名小明
# 学生姓名小红
# 学生姓名小李


#面试题:
#json.dump()  json.load()  这两个方法的参数是文件
#dumps()  loads() 参数是变量 

with open('07 天气接口返回数据.json', encoding='utf-8') as file:          
# txt gbk
    weather_obj = json.load(file)
    print(weather_obj)
    

对象转json的效果:
在这里插入图片描述
json转为pyhton对象的效果:
在这里插入图片描述
weather_obj的输出的效果:
在这里插入图片描述

请求天气接口示例

# 免费天气接口https://www.sojson.com/blog/305.html
import urllib.request
import json
# 101180101 郑州的天气接口
url = 'http://t.weather.sojson.com/api/weather/city/101180101'
resp = urllib.request.urlopen(url)
if resp.code == 200:
    weather_json = resp.read().decode('utf-8')
    # print(type(weather_json), weather_json)  # <class 'str'>
    weather_data = json.loads(weather_json)
    data = weather_data['data']
    # print('\n\n', data)

    today_humidity = data['shidu']
    today_pm25 = data['pm25']
    today_temperature = data['wendu']
    print(f'今天湿度:{today_humidity}, pm25:{today_pm25}, 温度:{today_temperature}')

# 输出的结果为:今天湿度:39%, pm25:33.0, 温度:0

请求5天的天气

方法一:

import json
import requests

# 输入地点
place = input("请输入天气地点:")
url = "http://wthrcdn.etouch.cn/weather_mini?city=%s" % (place)
response = requests.get(url)

# 将json文件格式导入成python的格式
weatherData = json.loads(response.text)

# 以好看的形式打印字典与列表表格
# import pprint
# pprint.pprint(weatherData)

w = weatherData['data']
print("地点:%s" % w['city'])

# 日期
date_a = []
# 最高温与最低温
highTemp = []
lowTemp = []
# 天气
weather = []
# 进行五天的天气遍历
for i in range(len(w['forecast'])):
    date_a.append(w['forecast'][i]['date'])
    highTemp.append(w['forecast'][i]['high'])
    lowTemp.append(w['forecast'][i]['low'])
    weather.append(w['forecast'][i]['type'])

    # 输出
    print("日期:" + date_a[i])
    print("\t温度:最" + lowTemp[i] + '℃~最' + highTemp[i] + '℃')
    print("\t天气:" + weather[i])
    print("")

print("\n今日着装:" + w['ganmao'])
print("当前温度:" + w['wendu'] + "℃")

效果如下图:
在这里插入图片描述
方法二:

import urllib.request
import json

url = 'http://t.weather.sojson.com/api/weather/city/101180101'
res = urllib.request.urlopen(url)
weather_json = res.read().decode('utf-8')
weather_data = json.loads(weather_json)
data = weather_data['data']
# print(data)

week = data['yesterday']['week']
print(f'周期:{week}')

# 日期     
data_a = []
ymd = []
week =[]
high = []
low = []
type =[]
notice =[]

for i in range(len(data['forecast'])):
    data_a.append(data['forecast'][i]['date'])
    ymd.append(data['forecast'][i]['ymd'])
    week.append(data['forecast'][i]['week'])
    high.append(data['forecast'][i]['high'])
    low.append(data['forecast'][i]['low'])
    type.append(data['forecast'][i]['type'])
    notice.append(data['forecast'][i]['notice'])

    print('日期:'+data_a[i])
    print('--')
    print('完整日期:' +ymd[i])
    print('周期:'+week[i])
    print(high[i] +low[i])
    print('天气:'+type[i])
    print('注意事项:'+notice[i])

在这里插入图片描述
方法三:

import urllib.request
import json

url = 'http://t.weather.sojson.com/api/weather/city/101180101'
res = urllib.request.urlopen(url)
weather_json = res.read().decode('utf-8')
weather_data = json.loads(weather_json)
data = weather_data['data']
# print(data)

week = data['yesterday']['week']
print(f'周期:{week}')

for i in range(len(data['forecast'])):
    week = data['forecast'][i]['week']
    ymd = data['forecast'][i]['ymd']
    high = data['forecast'][i]['high']
    low = data['forecast'][i]['low']
    fx = data['forecast'][i]['fx']
    fl = data['forecast'][i]['fl']
    type = data['forecast'][i]['type']
    notice = data['forecast'][i]['notice']


    print(f'周期:{week},{ymd}, {high}, {low}, {fx},{fl}, 天气:{type}, 注意事项:{notice} ')
    print('******')

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值