gpt4 book ai didi

python - 在 Python 中为 ansible callback_plugin 合并两个 json 字符串的更好方法

转载 作者:太空宇宙 更新时间:2023-11-04 10:33:16 35 4
gpt4 key购买 nike

我正在编写一个插件以将日志结果作为 ansible-playbook 的 json 文件返回。

我对 python 不是很熟悉,但我已经破解了一些似乎有效的东西:

def json_log(res, host):
if type(res) == type(dict()):
if 'verbose_override' not in res:
host_json = JSONEncoder().encode({'host':host})
result_json = JSONEncoder().encode(res)
combined_json = host_json + result_json
combined_json = combined_json.replace("}{", ',')
print(combined_json)

host_json 类似于:{"host": "centos65"}

result_json 类似于:{"cmd": "echo\"Hello World\"", "end": "2014-08-01 19:32:38.714584", "stdout": "Hello World", "changed": true, "start": "2014-08-01 19:32:38.707510", "delta": "0:00:00.007074", "stderr": "", "rc": 0, "invocation": {"module_name": "shell", "module_args": "echo\"Hello World\""}}

所以我选择了蛮力路线,只是组合了字符串并删除了 }{ 它到达了他们加入的地方,所以它将采用我想要的格式作为有效的 json:

{"host": "centos65","cmd": "echo\"Hello World\"", "end": "2014-08-01 19:32:38.714584", "stdout": "Hello World", "changed": true, "start": "2014-08-01 19:32:38.707510", "delta": "0:00:00.007074", "stderr": "", "rc": 0, "invocation": {"module_name": "shell", "module_args": "echo\"Hello World\""}}

所以现在我只是将两个字符串混合在一起,然后用逗号替换连接,有没有更聪明的方法将它们与位于 json 开头的主机部分组合起来?

最佳答案

res = {"cmd": "echo \"Hello World\" ", "end": "2014-08-01 19:32:38.714584", "stdout": "Hello World", "changed": True, "start": "2014-08-01 19:32:38.707510", "delta": "0:00:00.007074", "stderr": "", "rc": 0, "invocation": {"module_name": "shell", "module_args": "echo \"Hello World\""}}

def json_log(res, host):
if isinstance(res,dict) and 'verbose_override' not in res:
res.update({"host": host})
combined_json = JSONEncoder().encode(res)
print(combined_json)

In [73]: json_log(res,"centos")
{"cmd": "echo \"Hello World\" ", "end": "2014-08-01 19:32:38.714584", "stdout": "Hello World", "changed": true, "rc": 0, "start": "2014-08-01 19:32:38.707510", "host": "centos", "stderr": "", "delta": "0:00:00.007074", "invocation": {"module_name": "shell", "module_args": "echo \"Hello World\""}}

您可以用另一个字典的内容更新一个字典,您唯一会遇到的问题是如果您有重复的键并且不想覆盖值。

关于python - 在 Python 中为 ansible callback_plugin 合并两个 json 字符串的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25086586/

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