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'] + "℃")

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章