Python加载带有注释的Json文件实例
由于json文件不支持注释,所以如果在json文件中标记了注释,则使用python中的json.dump()无法加载该json文件。
本文旨在解决当定义“//”为json注释时,如何正确解析有注释的json文件。
程序实现
#encoding:utf-8
importjson
importre
importsys
reload(sys)
sys.setdefaultencoding('utf8')
CAUTION_PRINT_HEAD='caution:'
#创建一个xstr类,用于处理从文件中读出的字符串
classxstr:
def__init__(self,instr):
self.instr=instr
#删除“//”标志后的注释
defrmCmt(self):
qtCnt=cmtPos=slashPos=0
rearLine=self.instr
#rearline:前一个“//”之后的字符串,
#双引号里的“//”不是注释标志,所以遇到这种情况,仍需继续查找后续的“//”
whilerearLine.find('//')>=0:#查找“//”
slashPos=rearLine.find('//')
cmtPos+=slashPos
#print'slashPos:'+str(slashPos)
headLine=rearLine[:slashPos]
whileheadLine.find('"')>=0:#查找“//”前的双引号
qtPos=headLine.find('"')
ifnotself.isEscapeOpr(headLine[:qtPos]):#如果双引号没有被转义
qtCnt+=1#双引号的数量加1
headLine=headLine[qtPos+1:]
#printqtCnt
ifqtCnt%2==0:#如果双引号的数量为偶数,则说明“//”是注释标志
#printself.instr[:cmtPos]
returnself.instr[:cmtPos]
rearLine=rearLine[slashPos+2:]
#printrearLine
cmtPos+=2
#printself.instr
returnself.instr
#判断是否为转义字符
defisEscapeOpr(self,instr):
iflen(instr)<=0:
returnFalse
cnt=0
whileinstr[-1]=='\\':
cnt+=1
instr=instr[:-1]
ifcnt%2==1:
returnTrue
else:
returnFalse
#从json文件的路径JsonPath读取该文件,返回json对象
defloadJson(JsonPath):
try:
srcJson=open(JsonPath,'r')
except:
printCAUTION_PRINT_HEAD+'cannotopen'+JsonPath
quit()
dstJsonStr=''
forlineinsrcJson.readlines():
ifnotre.match(r'\s*//',line)andnotre.match(r'\s*\n',line):
xline=xstr(line)
dstJsonStr+=xline.rmCmt()
#printdstJsonStr
dstJson={}
try:
dstJson=json.loads(dstJsonStr)
returndstJson
except:
printCAUTION_PRINT_HEAD+JsonPath+'isnotavalidjsonfile'
quit()
#带缩进地在屏幕输出json字符串
defprintRes(resStr):
resStr=resStr.replace(',',',\n')
resStr=resStr.replace('{','{\n')
resStr=resStr.replace(':{',':\n{')
resStr=resStr.replace('}','\n}')
resStr=resStr.replace('[','\n[\n')
resStr=resStr.replace(']','\n]')
resStr=resStr
resArray=resStr.split('\n')
preBlank=''
forlineinresArray:
iflen(line)==0:
continue
lastChar=line[len(line)-1]
lastTwoChars=line[len(line)-2:]
iflastCharin{'}',']'}orlastTwoCharsin{'},','],'}:
preBlank=preBlank[:len(preBlank)-2]
try:
printpreBlank+line.decode('utf-8')
except:
print(preBlank+'[%Thislinecannotbedecoded%]')
iflastChar=='{'orlastChar=='[':
preBlank+=''*2
以上这篇Python加载带有注释的Json文件实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。