# 天氣預報
# 引入requests
import requests
# 引入python中內建的包json,用來解析和生成json資料
import json
city = input('請輸入要查詢的城市名稱:')
# url 統一資源定位符
# cmd 開啟命令列工具 輸入 pip install requests
url = ' %s &output=json&ak=tuegdhcvwi6forqnlm0qmxxy9n0okoiq&callback=?'%city
# 使用requests發起請求,接受返回的結果
rs = requests.get(url) #rs:# 使用loads函式,將json字串轉換為python的字典或列表
rs_dict = json.loads(rs.text)
# 取出error
error_code = rs_dict['error']
# 如果取出的error為0,表示資料正常,否則沒有查詢到結果
if error_code == 0:
# 從字典中取出資料
results = rs_dict['results']
# 根據索引取出城市天氣資訊字典
info_dict = results[0]
# 根據字典的key,取出城市名稱
city_name = info_dict['currentcity']
# 取出pm值
pm25 = info_dict['pm25']
print ('當前城市: %s pm值: %s'%(city_name,pm25))
# 取出天氣資訊列表
weather_data = info_dict['weather_data']
# for 迴圈取出每一天天氣的小字典
for weather_dict in weather_data:
# 取出日期,天氣,風級,溫度
date = weather_dict['date']
weather = weather_dict['weather']
wind = weather_dict['wind']
temperature = weather_dict['temperature']
print ('%s %s %s %s'%(date,weather,wind, temperature))
else:
print ('沒有查詢到天氣資訊')
python關於json檔案的讀取寫入實戰
一 理解 為什麼要用json模組的格式讀取寫入?1 由於python預設讀取write 寫入read 檔案的資料格式為字串 str 不能讀取寫入列表 字典等型別資料,所以需要採用json資料格式來儲存資料。2 json資料格式在多種語言中通用,有利於分享資料。二 python讀取寫入json格式分別...
JSON在android中應用
android裡面許可權控制的比較嚴,一般的應用當需要使用系統或者root許可權是,比較麻煩,所以編寫乙個root service用來處理root許可權請求,通過socket通訊 cpp view plain copy print?標準標頭檔案放在前面,否則有些函式定義會被覆蓋掉 include i...
python中的json解析
主要實現以下功能 解析 與構造json,即encoder and decoder 官方指導 中文教程 前者將obj轉化為json str,後者將str轉化為python物件,如果json字串是個object,轉化為dict,若是array則轉化為list json寫法 表示array的json字串 ...