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)

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

可以使用Python内置的csv和json模块来实现将csv文件转换为json文件的功能。下面是一个示例代码,可以将含有注释的csv文件转换为json文件: ```python import csv import json csv_file = 'data.csv' json_file = 'data.json' # 读取csv文件并解析数据 with open(csv_file, newline='') as csvfile: reader = csv.reader(csvfile) header = next(reader) # 读取表头 data = [] for row in reader: # 将每行数据和注释组成一个字典 item = {} for i, value in enumerate(row): item[header[i]] = value if i < len(header) - 1: item[header[i+1]+'_comment'] = '' # 初始化注释为空字符串 data.append(item) # 读取注释并填充到数据中 with open(csv_file, newline='') as csvfile: reader = csv.reader(csvfile) next(reader) # 跳过表头 for i, row in enumerate(reader): for j, value in enumerate(row): if j < len(header) - 1: comment_col = j + 1 comment = row[comment_col].strip() # 去除注释的前后空格 data[i][header[comment_col]+'_comment'] = comment # 将数据写入json文件 with open(json_file, 'w') as jsonfile: json.dump(data, jsonfile, indent=4) ``` 在这个示例代码中,我们首先使用csv模块读取csv文件中的数据,并将每行数据和注释组成一个字典。然后,我们再次读取csv文件,获取每行注释,并填充到数据字典中。最后,我们将数据写入json文件中,使用json模块的dump函数,同时指定indent参数来控制输出格式。 需要注意的是,这个示例代码假设csv文件中的注释位于每行数据的最后一列,并且注释的列名是数据列名后加上一个'_comment'的形式。如果csv文件中的注释列名不是这种形式,需要根据实际情况进行修改。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值