在 ini 文件中使用 JSON 路径

Use JSON path in ini file

我想从配置 json 文件中读取 json 值。我在 python 代码中使用的 json 对象路径如下所示:

jsonfile['Data'][0]['Tenants'][0]['TenPropertyGroup']

现在我想从 ini 文件传递​​上述路径 "['Data'][0]['Tenants'][0]['TenPropertyGroup']" 以确保如果对象路径在 json 文件中发生更改,我可以在 ini 文件中进行更改。

我的 config.ini 看起来像:

[CONFIG]
TenPropertyGroup= ['Data'][0]['Tenants'][0]['TenPropertyGroups']

我的 python 从 ini 文件读取后的代码看起来像

globalconfig = "config.ini"
config = configparser.ConfigParser()
config.read(globalconfig)

f = open(configfile, )
jsonfile = json.load(f)

TenPropertyGroup = config['CONFIG']['TenPropertyGroup']

TenPropertyGroups = (str(jsonfile ) + TenPropertyGroup)

但是当我使用 configparser 在 Python 中读取时,上面的 PropertyGroup 是字符串数据类型,我无法从 json 文件中获取列表。

我正在尝试从 python 代码中正确读取此 ini,但无法将其转换为对象。

我建议采用不同的方法。出于安全原因,您应该避免执行从文件读取的文本。如果您为 ini 文件值使用不同的格式,您可以解析它并使用这些值深入到您的 json 对象。这是一个简单的例子:

path_from_ini = 'x/y/z'

json_dict = { 'x' : { 'y' : { 'z' : 42 } } }

parts = path_from_ini.split('/')
v = json_dict

# Drill down into the JSON dictonary
for p in parts:
    v = v[p]

print(v)