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'] + "℃")
效果如下圖: