gpt4 book ai didi

Python搜索替换为多个Json对象

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:39:12 25 4
gpt4 key购买 nike

我不确定如何搜索它,但我正在尝试制作一个动态启动程序的脚本。我将有几个 JSON 文件,我希望能够进行搜索替换之类的事情。

所以我将设置一个示例:

配置.json

{
"global_vars": {
"BASEDIR": "/app",
"CONFIG_DIR": "{BASEDIR}/config",
"LOG_DIR": "{BASEDIR}/log",
"CONFIG_ARCHIVE_DIR": "{CONFIG_DIR}/archive"
}
}

然后是process.json

{
"name": "Dummy_Process",
"binary": "java",
"executable": "DummyProcess-0.1.0.jar",
"launch_args": "-Dspring.config.location={CONFIG_DIR}/application.yml -Dlogging.config={CONFIG_DIR}/logback-spring.xml -jar {executable}",
"startup_log": "{LOG_DIR}/startup_{name}.out"
}

现在我希望能够加载这两个 JSON 对象并能够使用其中的值进行更新。所以像 "CONFIG_ARCHIVE_DIR": "{CONFIG_DIR}/archive"会变成 CONFIG_ARCHIVE_DIR": "/app/config/archive"

有谁知道递归执行此操作的好方法,因为当我尝试使用诸如 CONFIG_DIR 之类的东西时遇到了问题,它首先需要 BASEDIR。

我有这个加载所有数据的函数:

#Recursive function, loops and loads all values into data
def _load_data(data,obj):
for i in obj.keys():
if isinstance(obj[i],str):
data[i]=obj[i]
if isinstance(obj[i],dict):
data=_load_data(data,obj[i])
return data

然后我有这个功能:

def _update_data(data,data_str=""):
if not data_str:
data_str=json.dumps(data)

for i in data.keys():
if isinstance(data[i],str):
data_str=data_str.replace("{"+i+"}",data[i])
if isinstance(data[i],dict):
data=_update_data(data,data_str)
return json.loads(data_str)

所以这适用于一个级别,但我不知道这是否是最好的方法。当我遇到像 CONFIG_DIR 这样的情况时它停止工作,因为它需要多次循环数据。首先它需要更新 BASEDIR,然后再次更新 CONFIG_DIR。欢迎提出建议。

这个脚本的最终目标是创建一个启动/停止/状态脚本来管理我们所有的二进制文件。他们都使用不同的二进制文件来启动,我想要一个进程文件用于多个服务器。每个进程都有一个服务器数组来告诉启动/停止脚本在给定服务器上运行什么。也许已经有这样的东西了,所以如果有的话,请指出我的方向。

我将在 Linux 上运行并且更喜欢使用 Python。我想要一些智能且易于其他人获取和使用/修改的东西。

最佳答案

我做了一些可以与您提供的示例文件一起使用的东西。请注意,我没有处理数据中的多个键或非字典。此函数接受在 JSON 解析您的输入文件后获得的字典列表。它利用了 re.sub 可以接受替换值的函数并在每次匹配时调用该函数这一事实。我确信可以对此进行大量改进,但至少应该让您入门。

def make_config(configs):
replacements = {}

def find_defs(config):
# Find leaf nodes of the dictionary.
defs = {}
for k, v in config.items():
if isinstance(v, dict):
# Nested dictionary so recurse.
defs.update(find_defs(v))
else:
defs[k] = v
return defs

for config in configs:
replacements.update(find_defs(config))

def make_replacement(m):
# Construct the replacement string.
name = m.group(0).strip('{}')
if name in replacements:
# Replace replacement strings in the replacement string.
new = re.sub('\{[^}]+\}', make_replacement, replacements[name])
# Cache result
replacements[name] = new
return new
raise Exception('Replacement string for {} not found'.format(name))

finalconfig = {}
for name, value in replacements.items():
finalconfig[name] = re.sub('\{[^}]+\}', make_replacement, value)

return finalconfig

有了这个输入:

[
{
"global_vars": {
"BASEDIR": "/app",
"CONFIG_DIR": "{BASEDIR}/config",
"LOG_DIR": "{BASEDIR}/log",
"CONFIG_ARCHIVE_DIR": "{CONFIG_DIR}/archive"
}
},
{
"name": "Dummy_Process",
"binary": "java",
"executable": "DummyProcess-0.1.0.jar",
"launch_args": "-Dspring.config.location={CONFIG_DIR}/application.yml -Dlogging.config={CONFIG_DIR}/logback-spring.xml -jar {executable}",
"startup_log": "{LOG_DIR}/startup_{name}.out"
}
]

它给出了这个输出:

{
'BASEDIR': '/app',
'CONFIG_ARCHIVE_DIR': '/app/config/archive',
'CONFIG_DIR': '/app/config',
'LOG_DIR': '/app/log',
'binary': 'java',
'executable': 'DummyProcess-0.1.0.jar',
'launch_args': '-Dspring.config.location=/app/config/application.yml -Dlogging.config=/app/config/logback-spring.xml -jar DummyProcess-0.1.0.jar',
'name': 'Dummy_Process',
'startup_log': '/app/log/startup_Dummy_Process.out'
}

关于Python搜索替换为多个Json对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44768391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com