罗钢主演的电视剧,开心的马骝谐音,北京稻香村地址
本文实例讲述了python sql查询并生成json文件操作。分享给大家供大家参考,具体如下:
1. 数据准备
sql数据点击此处。
2. python代码
import datetime import os import mssqlhelper ms = 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 arealist def getcity(provinces): citylist=ms.execquery("select *from dbo.cities where provinceid='%s'" % provinces) return citylist def getprovinces(): provlist=ms.execquery("select *from dbo.provinces") return provlist def createfilejson(): date=datetime.datetime.now().strftime('%y-%m-%d') path=date+'-provinces.json' return path def 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代码检验、检验、美化、格式化工具:
json在线格式化工具:
在线xml/json互相转换工具:
json代码在线格式化/美化/压缩/编辑/转换工具:
在线json压缩/转义工具:
更多python相关内容感兴趣的读者可查看本站专题:《python操作json技巧总结》、《python编码操作技巧总结》、《python数据结构与算法教程》、《python函数使用技巧总结》、《python字符串操作技巧汇总》、《python入门与进阶经典教程》及《python文件与目录操作技巧汇总》
希望本文所述对大家python程序设计有所帮助。
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Python 实现将numpy中的nan和inf,nan替换成对应的均值
python爬虫把url链接编码成gbk2312格式过程解析
网友评论