我计划对配置文件使用json,目前我有一个这样的配置
{
"settings": {
"general": "root",
"folder": "folder_test"
},
"TEST1": {
"dataone": "xyz",
"testing": {
"a": "$general/$folder/test.png",
"b": "$general/$folder/test.png"
},
"SOMELIST": [
"$general/$folder/test.png",
"$general/$folder/test.png"
]
},
"TEST2": {
"dataone": "xyz",
"testing": {
"a": "$general/$folder/test.png",
"b": "$general/$folder/test.png"
},
"something": {
"test_data": {
tester: {
"abc": "$general/$folder/test.png",
"zxv": "$general/$folder/test.png"
}
}
}
}
}
我的目的是让settings部分填充静态路径,如root和foldername等,并让config的其余部分贯穿整个config层次结构,以将设置用作变量。这是为了路径和文件夹的目的,如果根目录或新文件夹更改/添加,我在以后维护时不会有任何问题
我希望配置能够在以后的层次结构的任何级别中使用所有设置变量,即使在将来添加了新的级别
到目前为止,我只能循环一个级别,但不确定如何访问多个级别
for k, v in config.items():
for key in config.keys():
if key in v:
config[k] = v.replace("$" + key, config[key])
在stackoverflow的另一个主题中找到了这个,但这只是一个级别。我不知道如何建立一个通用的,可以在这里包括多个级别
您是否考虑过在将其解析为JSON之前只替换变量,而不是单独替换每个项目的变量?这样可以减少内存/计算成本,而且应该更容易
编辑:编写了一个递归替换函数。我希望你能读到它&;从中学习
这使用了相当多的函数调用。此配置没有问题,但另一个配置可能有问题
相关问题 更多 >
编程相关推荐