其他分享
首页 > 其他分享> > dict、json、yaml 之间相互转换

dict、json、yaml 之间相互转换

作者:互联网

定义一个字段:

dictConfig = {
    "version": 1,
    "formatters": {
        "formatter": {
            "format": "%(asctime)s %(levelname)-8s %(name)s [%(funcName)s(%(module)s:%(lineno)s)] %(message)s"
        },
        "simpleFormatter": {
            "format": "%(asctime)s %(levelname)-8s %(name)s [%(funcName)s(%(module)s:%(lineno)s)] %(message)s"
        },
    },
    "handlers": {
        "tcp_hendler": {
            "level": "WARNING",
            "class": "logging.handlers.SocketHandler",
            "host": "127.0.0.1",
            "port": "9020",
        },
        "console_handler": {
            "level": "DEBUG",
            "class": "logging.StreamHandler",
            "formatter": "formatter",
        },
        "file_handler": {
            "level": "DEBUG",
            "class": "logging.handlers.TimedRotatingFileHandler",
            "filename": "" + logs_dir + "\info.log",
            "when": "D",
            "backupCount": 3,
            "encoding": "utf-8",
            "formatter": "simpleFormatter",
        },
        "error_file_handler": {
            "level": "ERROR",
            "class": "logging.handlers.TimedRotatingFileHandler",
            "filename": "" + logs_dir + "\error.log",
            "when": "D",
            "backupCount": 3,
            "encoding": "utf-8",
            "formatter": "formatter",
        },
    },
    "loggers": {
        "logger": {
            "level": "DEBUG",
            "handlers": [
                "tcp_hendler",
                "console_handler",
                "file_handler",
                "error_file_handler",
            ],
        },
    },
}

将此字段转成json:

先导入import json

import json
with open('logconfig.txt', 'w',encoding='utf-8') as f: logconfig_json = json.dumps(dictConfig) f.write(logconfig_json)

将json转成字典格式

with open('logconfig.txt', 'r', encoding='utf-8') as f:
    logconfig_json = f.read()
    print(logconfig_json)
    dict = json.loads(logconfig_json)
    print(dict)

将字典转成yaml格式

先下载yaml:pip install pyyaml

import yaml
with open("logconfig.yaml", 'w', encoding='utf-8') as f: logconfig_yaml = yaml.dump(dictConfig) f.write(logconfig_yaml)
# 读取yaml文件的数据转成dict
with open('logconfig.yaml','r',encoding='utf-8') as f:
    ymal_dict = yaml.safe_load(f)
    print(ymal_dict)

 

标签:encoding,yaml,json,dict,formatter,logconfig
来源: https://www.cnblogs.com/amanda-yl/p/14813258.html