Python加載帶有注釋的Json文件實例
更新時間:2018年05月23日 14:40:07 作者:foolishwolfx
今天小編就為大家分享一篇Python加載帶有注釋的Json文件實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
由于json文件不支持注釋,所以如果在json文件中標(biāo)記了注釋,則使用python中的json.dump()無法加載該json文件。
本文旨在解決當(dāng)定義“//”為json注釋時,如何正確解析有注釋的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)建一個xstr類,用于處理從文件中讀出的字符串
class xstr:
def __init__(self, instr):
self.instr = instr
# 刪除“//”標(biāo)志后的注釋
def rmCmt(self):
qtCnt = cmtPos = slashPos = 0
rearLine = self.instr
# rearline: 前一個“//”之后的字符串,
# 雙引號里的“//”不是注釋標(biāo)志,所以遇到這種情況,仍需繼續(xù)查找后續(xù)的“//”
while rearLine.find('//') >= 0: # 查找“//”
slashPos = rearLine.find('//')
cmtPos += slashPos
# print 'slashPos: ' + str(slashPos)
headLine = rearLine[:slashPos]
while headLine.find('"') >= 0: # 查找“//”前的雙引號
qtPos = headLine.find('"')
if not self.isEscapeOpr(headLine[:qtPos]): # 如果雙引號沒有被轉(zhuǎn)義
qtCnt += 1 # 雙引號的數(shù)量加1
headLine = headLine[qtPos+1:]
# print qtCnt
if qtCnt % 2 == 0: # 如果雙引號的數(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對象
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文件實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- Python實現(xiàn)從文件中加載數(shù)據(jù)的方法詳解
- Python 保存加載mat格式文件的示例代碼
- python3+selenium獲取頁面加載的所有靜態(tài)資源文件鏈接操作
- python GUI庫圖形界面開發(fā)之PyQt5動態(tài)加載QSS樣式文件
- 解決Python 使用h5py加載文件,看不到keys()的問題
- python用pandas數(shù)據(jù)加載、存儲與文件格式的實例
- Python實現(xiàn)加載及解析properties配置文件的方法
- python web基礎(chǔ)之加載靜態(tài)文件實例
- python:關(guān)于文件加載及處理方式
相關(guān)文章
python實現(xiàn)搜索指定目錄下文件及文件內(nèi)搜索指定關(guān)鍵詞的方法
這篇文章主要介紹了python實現(xiàn)搜索指定目錄下文件及文件內(nèi)搜索指定關(guān)鍵詞的方法,可實現(xiàn)針對文件夾及文件內(nèi)關(guān)鍵詞的搜索功能,需要的朋友可以參考下2015-06-06
Python爬蟲爬取新浪微博內(nèi)容示例【基于代理IP】
這篇文章主要介紹了Python爬蟲爬取新浪微博內(nèi)容,結(jié)合實例形式分析了Python基于代理IP實現(xiàn)的微博爬取與抓包分析相關(guān)操作技巧,需要的朋友可以參考下2018-08-08
Django框架教程之正則表達(dá)式URL誤區(qū)詳解
正則表達(dá)式對大家來說應(yīng)該都不陌生,下面這篇文章主要給大家介紹了關(guān)于Django框架教程之正則表達(dá)式URL誤區(qū)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2018-01-01

