简体   繁体   English

在ini文件中使用JSON路径

[英]Use JSON path in ini file

I want to read the json values from config json file.我想从配置 json 文件中读取 json 值。 The json object path I use in my python code is like below:我在 python 代码中使用的 json 对象路径如下所示:

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

Now I want to pass this above path "['Data'][0]['Tenants'][0]['TenPropertyGroup']" from ini file to make sure I can make changes in ini file if the object path gets changed in json file.现在我想从 ini 文件中传递上面的路径"['Data'][0]['Tenants'][0]['TenPropertyGroup']"以确保如果对象路径发生更改,我可以在 ini 文件中进行更改在 json 文件中。

My config.ini looks like:我的config.ini看起来像:

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

My python code after reading from ini file looks like从ini文件读取后我的python代码看起来像

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

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

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

TenPropertyGroups = (str(jsonfile ) + TenPropertyGroup)

But when I am reading in Python using configparser the above PropertyGroup is of string data type and I am not able to get the list from json file.但是当我使用configparser在 Python 中阅读时,上面的 PropertyGroup 是字符串数据类型,我无法从 json 文件中获取列表。

I am trying to read this ini properly from python code but not able to convert it to object.我正在尝试从 python 代码中正确读取这个 ini,但无法将其转换为对象。

I would suggest a different approach.我会建议一种不同的方法。 You should avoid executing text read from a file for security reasons.出于安全原因,您应该避免执行从文件中读取的文本。 If you use a different format for you ini file value, you could parse it and use the values to drill down into you json object.如果你为你的ini文件值使用不同的格式,你可以解析它并使用这些值深入到你的 json 对象。 Here's a simple example:这是一个简单的例子:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM