python解析带注释的json文件,list转json,dict转json

import re
import json
import numpy as np
# rgex = re.compile(
# '(^)?[^\S\n]*/(?:\*(.*?)\*/[^\S\n]*|/[^\n]*)($)?',re.DOTALL | re.MULTILINE)

def select_line(line):
rgex = re.compile('[0-9]+(?:\.[0-9]+){0,3}')
ipos = line.find("//")
if ipos == -1 :
return line
line_str = line[ipos + 0]
if rgex.search(line_str):
return line[:ipos+16] + select_line(line[ipos + 17:])
else:
return line[:ipos] + select_line(line_str)

"""
解析json文件
"""
def parse_json(filename):
res = []
f = open(filename)
all_lines = f.readlines()
for line in all_lines:
l = select_line(line)
res.append(l)
result = []
isfind = False
for l in res:
if l.find("/*") != -1:
isfind = True
if not isfind:
result.append(l)
if l.find("*/") != -1:
isfind = False
newstr = ""
for i in result:
newstr += i
return json.loads(newstr)

"""
list类型 转 json文件
"""
def list_To_Json(lst):
keys = [str(x) for x in np.arange(len(lst))]
list_json = dict(zip(keys, lst))
str_json = json.dumps(list_json, indent=4, ensure_ascii=False)
return str_json
"""
dict类型 转 json文件
"""
def dict_To_Json(dictObj):
js_obj = json.dumps(dictObj, indent=4,ensure_ascii=False)
file_object = open('./Param/devs_config.ini', 'w')
file_object.write(js_obj)
file_object.close() # 最终写入的json文件格式:


if __name__ == '__main__':
jsdata = parse_json("/test.txt")
print(jsdata)




posted @ 2021-11-19 18:27  默*为  阅读(455)  评论(0编辑  收藏  举报