Python加載帶有注釋的Json文件實(shí)例
由于json文件不支持注釋,所以如果在json文件中標(biāo)記了注釋,則使用python中的json.dump()無法加載該json文件。
本文旨在解決當(dāng)定義“//”為json注釋時(shí),如何正確解析有注釋的json文件。
程序?qū)崿F(xiàn)
# encoding: utf-8 import json import re import sys reload(sys) sys.setdefaultencoding('utf8') CAUTION_PRINT_HEAD = 'caution: ' # 創(chuàng)建一個(gè)xstr類,用于處理從文件中讀出的字符串 class xstr: def __init__(self, instr): self.instr = instr # 刪除“//”標(biāo)志后的注釋 def rmCmt(self): qtCnt = cmtPos = slashPos = 0 rearLine = self.instr # rearline: 前一個(gè)“//”之后的字符串, # 雙引號(hào)里的“//”不是注釋標(biāo)志,所以遇到這種情況,仍需繼續(xù)查找后續(xù)的“//” while rearLine.find('//') >= 0: # 查找“//” slashPos = rearLine.find('//') cmtPos += slashPos # print 'slashPos: ' + str(slashPos) headLine = rearLine[:slashPos] while headLine.find('"') >= 0: # 查找“//”前的雙引號(hào) qtPos = headLine.find('"') if not self.isEscapeOpr(headLine[:qtPos]): # 如果雙引號(hào)沒有被轉(zhuǎn)義 qtCnt += 1 # 雙引號(hào)的數(shù)量加1 headLine = headLine[qtPos+1:] # print qtCnt if qtCnt % 2 == 0: # 如果雙引號(hào)的數(shù)量為偶數(shù),則說明“//”是注釋標(biāo)志 # print self.instr[:cmtPos] return self.instr[:cmtPos] rearLine = rearLine[slashPos+2:] # print rearLine cmtPos += 2 # print self.instr return self.instr # 判斷是否為轉(zhuǎn)義字符 def isEscapeOpr(self, instr): if len(instr) <= 0: return False cnt = 0 while instr[-1] == '\\': cnt += 1 instr = instr[:-1] if cnt % 2 == 1: return True else: return False # 從json文件的路徑JsonPath讀取該文件,返回json對(duì)象 def loadJson(JsonPath): try: srcJson = open(JsonPath, 'r') except: print CAUTION_PRINT_HEAD + 'cannot open ' + JsonPath quit() dstJsonStr = '' for line in srcJson.readlines(): if not re.match(r'\s*//', line) and not re.match(r'\s*\n', line): xline = xstr(line) dstJsonStr += xline.rmCmt() # print dstJsonStr dstJson = {} try: dstJson = json.loads(dstJsonStr) return dstJson except: print CAUTION_PRINT_HEAD + JsonPath + ' is not a valid json file' quit() # 帶縮進(jìn)地在屏幕輸出json字符串 def printRes(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 = '' for line in resArray: if len(line) == 0: continue lastChar = line[len(line)-1] lastTwoChars = line[len(line)-2:] if lastChar in {'}', ']'} or lastTwoChars in {'},', '],'}: preBlank = preBlank[:len(preBlank)-2] try: print preBlank + line.decode('utf-8') except: print(preBlank + '[%This line cannot be decoded%]') if lastChar == '{' or lastChar == '[': preBlank += ' '*2
以上這篇Python加載帶有注釋的Json文件實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- Python實(shí)現(xiàn)從文件中加載數(shù)據(jù)的方法詳解
- Python 保存加載mat格式文件的示例代碼
- python3+selenium獲取頁面加載的所有靜態(tài)資源文件鏈接操作
- python GUI庫圖形界面開發(fā)之PyQt5動(dòng)態(tài)加載QSS樣式文件
- 解決Python 使用h5py加載文件,看不到keys()的問題
- python用pandas數(shù)據(jù)加載、存儲(chǔ)與文件格式的實(shí)例
- Python實(shí)現(xiàn)加載及解析properties配置文件的方法
- python web基礎(chǔ)之加載靜態(tài)文件實(shí)例
- python:關(guān)于文件加載及處理方式
相關(guān)文章
解決Pytorch半精度浮點(diǎn)型網(wǎng)絡(luò)訓(xùn)練的問題
這篇文章主要介紹了解決Pytorch半精度浮點(diǎn)型網(wǎng)絡(luò)訓(xùn)練的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-05-05自適應(yīng)線性神經(jīng)網(wǎng)絡(luò)Adaline的python實(shí)現(xiàn)詳解
這篇文章主要介紹了自適應(yīng)線性神經(jīng)網(wǎng)絡(luò)Adaline的python實(shí)現(xiàn)詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09Pandas多個(gè)條件(AND,OR,NOT)中提取行
本文主要介紹了Pandas多個(gè)條件(AND,OR,NOT)中提取行,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02