【发布时间】:2014-08-14 21:23:00
【问题描述】:
我正在编写一个插件以将日志结果作为 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 开头的主机部分结合起来?
【问题讨论】:
标签: python json ansible ansible-playbook