您的位置:首页 > 编程语言 > Python开发

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)

这份代码解决了上述问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: