2016-08-02 6 views
2

私は現在、PythonのライブラリのConfigParserを使用しています:PythonのJSON Configを「拡張補間」

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を使用してください。しかし、私はそれがあなたの必要性であるかどうかは分かりません。これが可能なパッケージが1つあります。ベローは私がすべきことです。

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