在 Ansible 中将对象列表(字符串,字符串)转换为字典(字符串,列表<字符串>) [英] Convert list of objects (string, string) into Dictionary (string, list&lt;string&gt;) in Ansible

查看:179
本文介绍了在 Ansible 中将对象列表(字符串,字符串)转换为字典(字符串,列表<字符串>)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象列表(每个对象包含两个字符串类型的属性),我需要将其转换为字典.对象的第一个属性将成为键,对象的第二个属性必须组合成一个字符串列表.

我尝试了多种解决方案,但无法完全找到我需要的.

输入示例:

<预><代码>[{"name": "AAA",值":111"},{"name": "AAA",值":222"},{"name": "BBB",价值":333"},{"name": "BBB",值":444"},{"name": "CCC",价值":555"}]

期望的输出(任何一种都有效):

<预><代码>[{"name": "AAA",价值":[111",222"]},{"name": "BBB",价值":[333",444"]},{"name": "CCC",价值":[555"]}]

<预><代码>["AAA": [ "111", "222" ],"BBB": [ "333", "444" ],CCC":[555"]]

解决方案

下面的任务

- set_fact:my_list: "{{ my_list|default([]) +[{item.0: item.1|json_query('[].value')}] }}"循环:{{ input|groupby('name') }}"- 调试:变量:my_list

给予

"my_list": [{AAA":["111",222"]},{BBB":["333",444"]},{CCC":[555"]}]

I have a list of objects (each object contains two attributes of type string) which I need to convert into Dictionary. The first attribute of the object will become a key, the second attribute of the object would have to be combined into a list of strings.

I went through several solutions but couldn't find exactly what I need.

Input Example:

[
    {
        "name": "AAA",
        "value": "111"
    },
    {
        "name": "AAA",
        "value": "222"
    },
    {
        "name": "BBB",
        "value": "333"
    },
    {
        "name": "BBB",
        "value": "444"
    },
    {
        "name": "CCC",
        "value": "555"
    }
]

Desired Outputs (either one works):

[
    {
        "name": "AAA",
        "value": [ "111", "222" ]
    },
    {
        "name": "BBB",
        "value": [ "333", "444" ]
    },
    {
        "name": "CCC",
        "value": [ "555" ]
    }
]

[
    "AAA": [ "111", "222" ],
    "BBB": [ "333", "444" ],
    "CCC": [ "555" ]
]

解决方案

The tasks below

- set_fact:
    my_list: "{{ my_list|default([]) +
                 [{item.0: item.1|json_query('[].value')}] }}"
  loop: "{{ input|groupby('name') }}"
- debug:
    var: my_list

give

"my_list": [
    {
        "AAA": [
            "111", 
            "222"
        ]
    }, 
    {
        "BBB": [
            "333", 
            "444"
        ]
    }, 
    {
        "CCC": [
            "555"
        ]
    }
]

这篇关于在 Ansible 中将对象列表(字符串,字符串)转换为字典(字符串,列表<字符串>)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆