python腳本解析json文件
沒寫完。但是有效果。初次嘗試,寫的比較不簡潔。。。
比較煩的地方在於:
1,中文編碼:
pSpecs.decode('raw_unicode_escape')
2,花括號轉義:
{{
#!/usr/bin/python # -*- coding: UTF-8 -*- import os import json import sys reload(sys) sys.setdefaultencoding("utf-8") json_file = 'alink.json' #讀文件 md_file = 'alink.md' #寫文件 #寫入模版 protocol_templete ='## {pName}\n### [Format]\n```json\n {{\n "{property}":\"\"\n }}\n```\n### [Parameters]\n* {property};{pType};屬性說明.\n* specs:{pSpecs}\n\n\n' def writeServices(jsonObj): print(jsonObj) pName = jsonObj["name"]; # pType = jsonObj["type"]; def writeProperty( jsonObj ): pName = jsonObj["name"]; property = jsonObj["identifier"]; pType = jsonObj["dataType"]["type"] pSpecs = json.dumps(jsonObj["dataType"]["specs"]) print(pSpecs.decode('raw_unicode_escape')) //解決中文編碼問題 # print(protocol_templete.format(pName="".join(pName),pType=pType,pSpecs=pSpecs,property="".join(property))) # writeFile(protocol_templete) writeFile(protocol_templete.format(pName="".join(pName),pType=pType,pSpecs=pSpecs.decode('raw_unicode_escape'),property="".join(property))) def writeEvent(jsonObj): print(jsonObj) #追加文件內容 def writeFile(str): with open(md_file, 'a+') as fo: fo.write(str) fo.close(); def handleJson(alinkDic): # print(str(alinkDic)) # services = alinkDic["services"]# print(services) for k in alinkDic.keys(): list = ["services","events","properties"] if(k in list) : writeFile("## %s\n"%k) values = alinkDic[k] #list if(k == "services"): map(writeServices,values) elif(k == "events"): map(writeEvent,values) else: map(writeProperty,values) if __name__ == '__main__': if os.path.exists(json_file): fileContent = open(json_file).read(); #清空文件 with open(md_file, 'wb+') as file: file.close(); jsonDic = json.loads(fileContent) # print(open(json_file).read()); //打印json文件 handleJson(jsonDic) # print(json.loads(''.join(open(json_file).readlines()))) //json對象轉換成python對象 else: print 'json 配置文件不存在'
