python脚本解析json文件

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 配置文件不存在'

猜你喜欢

转载自www.cnblogs.com/developer-qin/p/9510363.html