在Ansible中将对象列表(字符串,字符串)转换为字典(字符串,list< string>) [英] Convert list of objects (string, string) into Dictionary (string, list<string>) in Ansible
本文介绍了在Ansible中将对象列表(字符串,字符串)转换为字典(字符串,list< string>)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个对象列表(每个对象包含两个类型为string的属性),我需要将其转换为Dictionary.该对象的第一个属性将成为键,该对象的第二个属性将必须组合成字符串列表.
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.
输入示例:
[
{
"name": "AAA",
"value": "111"
},
{
"name": "AAA",
"value": "222"
},
{
"name": "BBB",
"value": "333"
},
{
"name": "BBB",
"value": "444"
},
{
"name": "CCC",
"value": "555"
}
]
所需的输出(两者均可行):
[
{
"name": "AAA",
"value": [ "111", "222" ]
},
{
"name": "BBB",
"value": [ "333", "444" ]
},
{
"name": "CCC",
"value": [ "555" ]
}
]
[
"AAA": [ "111", "222" ],
"BBB": [ "333", "444" ],
"CCC": [ "555" ]
]
推荐答案
以下任务
- set_fact:
my_list: "{{ my_list|default([]) +
[{item.0: item.1|json_query('[].value')}] }}"
loop: "{{ input|groupby('name') }}"
- debug:
var: my_list
给予
"my_list": [
{
"AAA": [
"111",
"222"
]
},
{
"BBB": [
"333",
"444"
]
},
{
"CCC": [
"555"
]
}
]
这篇关于在Ansible中将对象列表(字符串,字符串)转换为字典(字符串,list< string>)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文