【Python】将json字符串配置存储为.py配置文件

时间:2024-03-17 14:18:09

将json转换为config
json结构为:
在这里插入图片描述

import json


def convert_json_to_config(json_str):
    json_data = json.loads(json_str)

    config_dict = {}
    for key, value in json_data.items():
        keys = key.split(".")
        section = keys[0]
        option = ".".join(keys[1:])
        if len(keys) == 1:
            config_dict[section] = value
        else:
            if section not in config_dict:
                config_dict[section] = {}

            if "." in option:
                nested_section, nested_option = option.split(".", 1)
                if nested_section not in config_dict[section]:
                    config_dict[section][nested_section] = {}
                config_dict[section][nested_section][nested_option] = value
            else:
                config_dict[section][option] = value

    return config_dict

写入到文件

def write_config_to_file(config_dict, file_path):
    with open(file_path, "w") as file:
        for section, options in config_dict.items():
            file.write(f"{section} = {json.dumps(options, indent=4)}\n\n")

测试

if __name__ == "__main__":
    json_str = '{"config1":"value1","config2.subconfig1":"value2","config2.subconfig2.subconfig3":"value2", "config2.subconfig2.subconfig4":"value4","config3":"value5"}'

    config_dict = convert_json_to_config(json_str)

    write_config_to_file(config_dict, "config.py")

结果
在这里插入图片描述