json文件处理
常用的模块
- json - 内置
- json5 - 可以解析带注释的文件
- ujson
- ojson
打印带缩进的 json
def print_dict(obj:dict, indent:int = 4) -> str:
import json
print("yaml_json: ", json.dumps(obj, indent=indent, ensure_ascii=False))
传统 json 文件处理
- 从 json 文件读取
with open('./test.json', encoding='utf8') as f:
hwnd_info = json.loads(f.read())
带注释的 json 文件处理
json5 模块
- 安装
python -m pip install json5
- 使用 - 跟内置的 json 模块类似
import json5
with open('./test.json', encoding='utf8') as f:
hwnd_info = json5.loads(f.read())
原生自己写(不推荐)
- 定义
# 读取带注释 // /* */ 的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)