2016-08-02 55 views
2

我目前正在使用Python庫configparser:Python中的Json配置「擴展插值」

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'?

回答

0

嘗試使用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文件定義的鍵。

+0

但您無法替換'$ {parent.child}'路徑 – vsminkov