Python 读取带有注释的JSON文件

本文介绍了一种处理带有注释的JSON文件的方法,并提供了一个Python实现的示例,该示例能够有效地移除JSON文件中的注释,以便进行后续的数据解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)

这份代码解决了上述问题。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值