Python 读取带有注释的JSON文件
2018-01-24 14:49
441 查看
Python 读取带有注释的JSON文件
在读取json文件时,有时会遇到文件中含有注释时,会报Expecting property name: line 12 column 3 (char 268)
意思即在文件12列3行处存在不符合JSON格式的字符,也就是注释。
要想解析这个JSON文件,必须要去除文件中的注释,在node.js中有专门去除注释的第三方包 strip-json-comments,但很可惜在python中不存在这样的包。
在网上找到了一份代码
import json import re # Regular expression for comments comment_re = re.compile( '(^)?[^\S\n]*/(?:\*(.*?)\*/[^\S\n]*|/[^\n]*)($)?', re.DOTALL | re.MULTILINE ) def parse_json(filename): """ Parse a JSON file First remove comments and then use the json module package Comments look like : // ... or /* ... */ """ with open(filename) as f: content = ''.join(f.readlines()) ## Looking for comments match = comment_re.search(content) while match: # single line comment content = content[:match.start()] + content[match.end():] match = comment_re.search(content) print content # Return json file return json.loads(content)
可以去除形如
// ....
/* .... */
的注释,但在去除第一种注释时,可能会有误伤,比如说JSON文件中有这样一个键值队
"url": "http://127.0.0.1:16666",
http: 后面的 //127.0.0.1:16666”则会被去除,看来还是得自己写一套
# 读取带注释 // /* */ 的json文件 def parse_json(self,filename): """ Parse a JSON file First remove comments and then use the json module package Comments look like : // ... or /* ... */ """ res = [] f = open(filename) all_lines = f.readlines() #去除形如 // 但不包括 http:// ip_addr 的注释 for line in all_lines: l = self.strip_comment(line) res.append(l) result = [] comment = False #去除形如 /* */的注释 for l in res: if l.find("/*") != -1: comment = True if not comment: result.append(l) if l.find("*/") != -1: comment = False #若直接使用 json.loads(str(res)) 会报 "ValueError: No JSON object could be decoded" str_res = "" for i in result: str_res += i return json.loads(str_res) def strip_comment(self,line): #匹配IP地址的正则表达式 ip_re = re.compile('[0-9]+(?:\.[0-9]+){0,3}') index = line.find("//") if index == -1 : return line line_str = line[index + ] if ip_re.search(line_str): return line[:index+16] + self.strip_comment(line[index+17:]) else: return line[:index] + self.strip_comment(line_str)
这份代码解决了上述问题。
相关文章推荐
- Python加载带有注释的Json文件
- Python加载带有注释的Json文件实例
- Python读取和写入json文件
- python json及mysql——读取json文件存sql、数据库日期类型转换、终端操纵mysql及python codecs读取大文件问题
- Python json文件读取及显示中文乱码的问题
- python读取和存储dict()与.json格式文件
- Python——保存、读取json文件
- python学习笔记十六:读取JSON文件
- python 读取json文件
- python读取json文件,并将数据插入到mongodb
- Python实现读取json文件到excel表
- 读取json文件——python入门
- python解析json文件读取Android permission说明
- python读取和存储dict()与.json格式文件
- python 读取 json文件
- python.json/pygal.maps.world学习范例-读取json格式文件、生成世界地图
- python 读取文件以及对文件的json字符串的操作
- python读取json文件并将数据插入到mongodb的方法
- 利用python读取带有中文的字符串,和将带有中文的字符串写到txt文件中
- python json及mysql——读取json文件存sql、数据库日期类型转换、终端操纵mysql及python codecs读取大文件问题