Python Json 配置 'Extended Interpolation'

标签 python json configparser

我目前正在使用 Python 库 configparser:

from configparser import ConfigParser, ExtendedInterpolation

我发现 ExtendedInterpolation 非常有用,因为它避免了必须在多个地方重新输入常量的风险。

我现在需要使用 Json 文档作为配置的基础,因为它提供了更多结构。

import json
from collections import OrderedDict

def get_json_config(file):
    """Load Json into OrderedDict from file"""

    with open(file) as json_data:
        d = json.load(json_data, object_pairs_hook=OrderedDict)

    return d

对于实现 configparser 风格的 ExtendedInterpolation 的最佳方式,有人有什么建议吗?

例如,如果 Json 中的节点包含值 ${home_dir}/lumberjack,这将复制根节点 home_dir 并取值“lumberjack”?

最佳答案

尝试使用string.Template。但我不确定这是否是你的需要。有一个包可以做到这一点。贝娄是我应该做的。

config.json

{
    "home_dir": "/home/joey",
    "class_path": "/user/local/bin",
    "dir_one": "${home_dir}/dir_one", 
    "dir_two": "${home_dir}/dir_two", 

    "sep_path_list": [
        "${class_path}/python",
        "${class_path}/ruby",
        "${class_path}/php"
    ]
}

python 代码:

import json
from string import Template

with open("config.json", "r") as config_file:
    config_content = config_file.read()
    config_template = Template(config_content)
    mid_json = json.loads(config_content)
    config = config_template.safe_substitute(mid_json)

    print config

这可以替换json文件中定义的key。

关于Python Json 配置 'Extended Interpolation',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38716890/

相关文章:

Python 深度合并字典数据

java - 比较包含对象列表的同一类的两个对象

java - Web 服务 - 在 Java 中为 RESTful Web 服务配置 JSON

python - 如何在 Python 中加载配置文件并能够使用点表示法(属性)访问值?

python - 在动态属性设置上绕过 mypy 的 "Module has no attribute"

python - 如何统计pandas中DataFrame两列的定义值差的个数?

python - 可迭代 float ?

python-3.x - Python - KeyError(key) 被引发,但它不应该

python - 在 python 中精确 sleep

python - 如何使用 python 在 JSON 输出上显示所有字符串匹配