【问题标题】:Need to map json to list需要将json映射到list
【发布时间】:2020-02-08 12:39:09
【问题描述】:

我有以下 json 作为值的注册变量,需要从这个 JSON 中提取名称和 dn 以列出。使用 set_fact 尝试了不同的选项,但没有任何运气。

{
    "nodes": {
        "status": -1,
        "imdata": [
            {
                "fabricNode": {
                    "attributes": {
                        "status": "",
                        "dn": "topology/pod-1/node-1",
                        "name": "NOQCJALAB1"
                    }
                }
            },
            {
                "fabricNode": {
                    "attributes": {
                        "status": "",
                        "dn": "topology/pod-1/node-1",
                        "name": "NOQCJALAB2"
                    }
                }
            }
        ],
        "totalCount": 2,
        "changed": false,
        "failed": false
    },
    "changed": false,
    "_ansible_verbose_always": true,
    "_ansible_no_log": false
}

【问题讨论】:

    标签: ansible yaml


    【解决方案1】:

    您需要删除对map('from_json') 的无关调用,因为该对象已经是dict

    - set_fact:
        node_names: >-
          {{ (nodes.stdout | from_json).data
          | map(attribute='fabnode')
          | map(attribute='attributes')
          | map(attribute='dn')
          | list
          }}
    

    如果您的数据结构包含 嵌入式 JSON,您只需要那些 map('from_json') 调用,如下所示:

    - set_fact:
         inner_value: >-
            {{ (example_text | from_json).a_key
            | map("from_json")
            | map(attribute="inner_key")
            | list
            }}
      vars:
        example_text: |
          {"a_key": ["{\"inner_key\": \"inner value\"}"]}
    

    【讨论】:

    • 可以请指导我上面的 JSON 吗?在数组中我有另一个 JSON,这是我感到困惑的地方,因为我对 ansible 比较陌生
    【解决方案2】:

    可以使用json_query。例如下面的任务

    - set_fact:
        my_list: "{{ nodes.imdata|
                     json_query('[].{dn: fabricNode.attributes.dn,
                                     name: fabricNode.attributes.name}')
                                     }}"
    - debug:
        var: my_list
    

    "my_list": [
        {
            "dn": "topology/pod-1/node-1", 
            "name": "NOQCJALAB1"
        }, 
        {
            "dn": "topology/pod-1/node-1", 
            "name": "NOQCJALAB2"
        }
    ]
    

    【讨论】:

    • 简单极品!非常感谢。我们可以用一个简单的 json 代替 json 数组吗?
    • 对不起,我是新来的。由于我现在无法详细编辑,因此我将在以后适当地发布。 Json 数组看起来不错。非常感谢
    • 您好,如果您在 imdata 中还有一个数组,请您指导我吗?数组中的数组
    猜你喜欢
    • 2017-11-25
    • 1970-01-01
    • 2018-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多