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('******')