Python加载带有注释的Json文件实例


Posted in Python onMay 23, 2018

由于json文件不支持注释,所以如果在json文件中标记了注释,则使用python中的json.dump()无法加载该json文件。

本文旨在解决当定义“//”为json注释时,如何正确解析有注释的json文件。

程序实现

# encoding: utf-8
import json
import re
import sys
reload(sys)
sys.setdefaultencoding('utf8')
CAUTION_PRINT_HEAD = 'caution: '
# 创建一个xstr类,用于处理从文件中读出的字符串
class xstr:
 def __init__(self, instr):
  self.instr = instr
 # 删除“//”标志后的注释
 def rmCmt(self): 
  qtCnt = cmtPos = slashPos = 0
  rearLine = self.instr
  # rearline: 前一个“//”之后的字符串,
  # 双引号里的“//”不是注释标志,所以遇到这种情况,仍需继续查找后续的“//”
  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]): # 如果双引号没有被转义
     qtCnt += 1 # 双引号的数量加1
    headLine = headLine[qtPos+1:]
    # print qtCnt
   if qtCnt % 2 == 0: # 如果双引号的数量为偶数,则说明“//”是注释标志
    # print self.instr[:cmtPos]
    return self.instr[:cmtPos]
   rearLine = rearLine[slashPos+2:]
   # print rearLine
   cmtPos += 2
  # print self.instr
  return self.instr
 # 判断是否为转义字符
 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()
# 带缩进地在屏幕输出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文件实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python遍历文件夹和读写文件的实现方法
May 10 Python
Python使用wxPython实现计算器
Jan 30 Python
Python读取excel中的图片完美解决方法
Jul 27 Python
使用Python的toolz库开始函数式编程的方法
Nov 15 Python
Python类的继承用法示例
Jan 31 Python
python os.fork() 循环输出方法
Aug 08 Python
Python3.6 + TensorFlow 安装配置图文教程(Windows 64 bit)
Feb 24 Python
python+selenium+Chrome options参数的使用
Mar 18 Python
公认8个效率最高的爬虫框架
Jul 28 Python
Python爬虫之爬取淘女郎照片示例详解
Jul 28 Python
python中lower函数实现方法及用法讲解
Dec 23 Python
用Python自动清理系统垃圾的实现
Jan 18 Python
Python实现判断一行代码是否为注释的方法
May 23 #Python
对python的文件内注释 help注释方法
May 23 #Python
Python基于生成器迭代实现的八皇后问题示例
May 23 #Python
Pycharm 操作Django Model的简单运用方法
May 23 #Python
PyCharm代码格式调整方法
May 23 #Python
创建pycharm的自定义python模板方法
May 23 #Python
对Python中9种生成新对象的方法总结
May 23 #Python
You might like
php,不用COM,生成excel文件
2006/10/09 PHP
使用php+apc实现上传进度条且在IE7下不显示的问题解决方法
2013/04/25 PHP
joomla jce editor 解决上传中文名文件失败问题
2013/06/09 PHP
PHP源码分析之变量的存储过程分解
2014/07/03 PHP
PHP 二维关联数组根据其中一个字段排序(推荐)
2017/04/04 PHP
php 输出缓冲 Output Control用法实例详解
2020/03/03 PHP
Prototype使用指南之selector.js
2007/01/10 Javascript
jQuery+ajax实现顶一下,踩一下效果
2010/07/17 Javascript
javascript中onclick(this)用法介绍
2013/04/19 Javascript
使用javascript实现Iframe自适应高度
2014/12/24 Javascript
jquery实现触发时更新下拉列表内容的方法
2015/12/02 Javascript
Position属性之relative用法
2015/12/14 Javascript
javascript设计模式之模块模式学习笔记
2017/02/15 Javascript
react-router实现按需加载
2017/05/09 Javascript
详解JS数据类型的值拷贝函数(深拷贝)
2017/07/13 Javascript
AngularJS中scope的绑定策略实例分析
2017/10/30 Javascript
JS实现打字游戏
2019/12/17 Javascript
Element Popover 弹出框的使用示例
2020/07/26 Javascript
[41:52]2018DOTA2亚洲邀请赛3月29日小组赛B组Effect VS Secret
2018/03/30 DOTA
[50:05]VGJ.S vs OG 2018国际邀请赛淘汰赛BO3 第二场 8.22
2018/08/23 DOTA
Python彩色化Linux的命令行终端界面的代码实例分享
2016/07/02 Python
Python遍历目录中的所有文件的方法
2016/07/08 Python
Python+matplotlib+numpy实现在不同平面的二维条形图
2018/01/02 Python
python实现烟花小程序
2019/01/30 Python
pandas 数据索引与选取的实现方法
2019/06/21 Python
python实现读取excel文件中所有sheet操作示例
2019/08/09 Python
Python Opencv提取图片中某种颜色组成的图形的方法
2019/09/19 Python
Django app配置多个数据库代码实例
2019/12/17 Python
文件上传服务器-jupyter 中python解压及压缩方式
2020/04/22 Python
Python通过字典映射函数实现switch
2020/11/06 Python
CSS3实现头像旋转效果
2017/03/13 HTML / CSS
豪华床上用品、床单和浴室必需品:Peacock Alley
2019/09/04 全球购物
生日主持词
2014/03/20 职场文书
副职竞争上岗演讲稿
2014/05/12 职场文书
党员应该树立反腐倡廉的坚定意识思想汇报
2014/09/12 职场文书
甲乙双方合作协议书
2014/10/13 职场文书