Python 读取带有注释的JSON文件 |
您所在的位置:网站首页 › 扬子江船业股票市值多少钱 › 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)这份代码解决了上述问题。 |
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |