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

时间:2014-08-01 18:37:28

标签: python json ansible ansible-playbook

我正在编写一个插件,将日志结果作为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开头的主机部分组合在一起?

2 个答案:

答案 0 :(得分:2)

由于它们都是字典,因此您可以使用另一个字典更新两个字典中的一个。例如:

>>> a = {"host": "centos65"}

>>> b = {"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\""}}

>>> a.update(b)
>>> a
{'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': 'centos65', 'stderr': '', 'delta': '0:00:00.007074', 'invocation': {'module_name': 'shell', 'module_args': 'echo "Hello World"'}}
>>> a["host"]
'centos65'
>>> a["cmd"]
'echo "Hello World" '
>>> 

答案 1 :(得分:2)

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\""}}

您可以使用另一个内容更新dict,唯一的问题是,如果您有重复的密钥并且不希望覆盖这些值。