本文實例講述了Python SQL查詢并生成json文件操作。分享給大家供大家參考,具體如下:
1. 數據準備
SQL數據點擊此處本站下載。
2. python代碼
import datetime import osimport mssqlhelperms = mssqlhelper.MSSQL(host="192.168.0.108", user="sa", pwd="sa", db="ComPrject")def getAreas(cityid): arealist=ms.ExecQuery("select *From dbo.areas where cityid='%s' " % cityid) return arealistdef getCity(provinces): citylist=ms.ExecQuery("select *From dbo.cities where provinceid='%s'" % provinces) return citylistdef getProvinces(): provlist=ms.ExecQuery("select *From dbo.provinces") return provlistdef createFileJson(): date=datetime.datetime.now().strftime('%Y-%m-%d') path=date+'-provinces.json' return pathdef writeJson(path): provlist=getProvinces() with open(path,"w+",encoding="utf-8") as f: f.write("[") lp = 0 for p in provlist: if lp>0: f.write(",/n") else: f.write("/n") f.write("{/n") f.write('"Code":"%s"/n'% p[1]) f.write(',"Name":"%s"/n'% p[2]) f.write(',Nodes:[/n') citylist=getCity(p[1]) lc = 0 for c in citylist: if lc>0: f.write("/t,/n") else: f.write("/n") f.write("/t{/n") f.write('/t"Code":"%s"/n'% c[1]) f.write('/t,"Name":"%s"/n'% c[2]) f.write('/t,Nodes:[/n') arealist = getAreas(c[1]) la = 0 for a in arealist: if la>0: f.write("/t/t,/n") else: f.write("/n") f.write("/t/t{/n") f.write('/t/t"Code":"%s"/n'% a[1]) f.write('/t/t,"Name":"%s"/n'% a[2]) f.write("/t/t}/n") la += 1 f.write("/t]/n") f.write("/t}/n") lc += 1 f.write("]/n") f.write("}/n") lp += 1 f.write("]/n")if __name__ == '__main__': path=createFileJson() writeJson(path)
3.生成預覽
PS:這里再為大家推薦幾款比較實用的json在線工具供大家參考使用:
在線JSON代碼檢驗、檢驗、美化、格式化工具:
http://tools.jb51.net/code/json
JSON在線格式化工具:
http://tools.jb51.net/code/jsonformat
在線XML/JSON互相轉換工具:
http://tools.jb51.net/code/xmljson
json代碼在線格式化/美化/壓縮/編輯/轉換工具:
http://tools.jb51.net/code/jsoncodeformat
在線json壓縮/轉義工具:
http://tools.jb51.net/code/json_yasuo_trans
更多Python相關內容感興趣的讀者可查看本站專題:《Python操作json技巧總結》、《Python編碼操作技巧總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答