Python Ansible JSON输出

时间:2018-08-06 23:07:27

标签: python json ansible

我得到了json输出。我该如何获取可以存储为变量的键

示例:

"plays": [
{
    "tasks": [
        {
          "hosts": {
            "sw01": {
              "_ansible_no_log": false,
              "action": "set_fact",
              "ansible_facts": {
                "OS": "ios"
              },
              "changed": false
            }
          }
    ]
}]

获取变量:

    FACTS = output['plays'][0]['tasks'][0]['hosts']

喜欢获取:sw01并存储为主机名。然后获取OS值。 感谢您的帮助

1 个答案:

答案 0 :(得分:0)

这是完整版

import json

data = """{
        "plays": [
            {
                "tasks": [
                    {
                    "hosts": {
                                "sw01": {
                                "_ansible_no_log": false,
                                "action": "set_fact",
                                "ansible_facts": {
                                    "OS": "ios"
                                },
                                "changed": false
                                }
                    }
                    }]
            }]
        }"""

output = json.loads(data)

hosts = output['plays'][0]['tasks'][0]['hosts']
for host in hosts.keys():
    print(host)