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 time模块用法实例详解
Sep 11 Python
python批量生成本地ip地址的方法
Mar 23 Python
分享几道你可能遇到的python面试题
Jul 24 Python
Python实现处理逆波兰表达式示例
Jul 30 Python
计算机二级python学习教程(3) python语言基本数据类型
May 16 Python
django重新生成数据库中的某张表方法
Aug 28 Python
Python利用matplotlib绘制约数个数统计图示例
Nov 26 Python
pytorch 改变tensor尺寸的实现
Jan 03 Python
Python使用type动态创建类操作示例
Feb 29 Python
pytorch 查看cuda 版本方式
Jun 23 Python
linux mint中搜狗输入法导致pycharm卡死的问题
Oct 28 Python
python 基于opencv实现高斯平滑
Dec 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&amp;mysql(二)
2006/10/09 PHP
php部分常见问题总结
2008/03/27 PHP
PHP生成excel时单元格内换行问题的解决方法
2010/08/26 PHP
php使用百度ping服务代码实例
2014/06/19 PHP
PHP生成二维码的两个方法和实例
2014/07/01 PHP
PHP伪静态Rewrite设置之APACHE篇
2014/07/30 PHP
php上传功能集后缀名判断和随机命名(强力推荐)
2015/09/10 PHP
PHP实现的mysql主从数据库状态检测功能示例
2017/07/20 PHP
laravel框架中控制器的创建和使用方法分析
2019/11/23 PHP
php字符串函数 str类常见用法示例
2020/05/15 PHP
JS正则中的RegExp对象对象
2012/11/07 Javascript
js中return false(阻止)的用法
2013/08/14 Javascript
js特殊字符转义介绍
2013/11/05 Javascript
使用AngularJS创建自定义的过滤器的方法
2015/06/18 Javascript
JavaScript中eval()函数用法详解
2015/12/14 Javascript
JavaScript仿微博输入框效果(案例分析)
2016/12/06 Javascript
JavaScript中transform实现数字翻页效果
2017/03/08 Javascript
Jquery获取radio选中的值
2017/05/05 jQuery
Vue.js中关于侦听器(watch)的高级用法示例
2018/05/02 Javascript
vue点击input弹出带搜索键盘并监听该元素的方法
2018/08/25 Javascript
在Python的Django框架中加载模版的方法
2015/07/16 Python
python实现域名系统(DNS)正向查询的方法
2016/04/19 Python
Android基于TCP和URL协议的网络编程示例【附demo源码下载】
2018/01/23 Python
Python 实现两个服务器之间文件的上传方法
2019/02/13 Python
python实现图片转字符小工具
2019/04/30 Python
OpenCV 模板匹配
2019/07/10 Python
Pycharm 2020.1 版配置优化的详细教程
2020/08/07 Python
Python爬虫之Selenium下拉框处理的实现
2020/12/04 Python
Origins加拿大官网:雅诗兰黛集团高端植物护肤品牌
2017/11/19 全球购物
美国伊甸园兄弟种子公司:Eden Brothers
2018/07/01 全球购物
基层党员公开承诺书
2014/05/29 职场文书
环境科学专业教师求职信
2014/07/12 职场文书
2015年个人审计工作总结
2015/04/07 职场文书
2015年调度员工作总结
2015/04/30 职场文书
学生会主席任命书
2015/09/21 职场文书
Goland使用Go Modules创建/管理项目的操作
2021/05/06 Golang