我有一个Ansible作业运行在2个或更多的url上。每个url返回相同的变量,但值不同。下面是该作业的JSON数据注册表:
{
"msg": {
"results": [
{
"url": "http://0.0.0.1:xxx1",
"othervar": "othervar",
"othervar2": "othervar2",
"json": {
"messages": [
{
"message": "This is message number 1",
"message2": "This is message2 number 1"
},
{
"message": "This is message number 2",
"message2": "This is message2 number 2"
},
{
"message": "This is message number 3",
"message2": "This is message2 number 3"
}
]
}
},
{
"url": "http://0.0.0.2:xxx2",
"othervar": "othervar",
"othervar2": "othervar2",
"json": {
"messages": [
{
"message": "This is message number 1",
"message2": "This is message2 number 1"
},
{
"message": "This is message number 2",
"message2": "This is message2 number 2"
},
{
"message": "This is message number 3",
"message2": "This is message2 number 3"
}
]
}
}
]
}
}
我想创建一个只包含url
变量以及message
和message2
变量的特定dict。对于预期结果,我有两种选择:
备选案文1:
"message": [
{
"url": "http://0.0.0.1:xxx1",
"content": [
{
"message": "This is message number 1",
"message2": "This is message2 number 1"
},
{
"message": "This is message number 2",
"message2": "This is message2 number 2"
},
{
"message": "This is message number 3",
"message2": "This is message2 number 3"
}
]
},
{
"url": "http://0.0.0.2:xxx2",
"content": [
{
"message": "This is message number 1",
"message2": "This is message2 number 1"
},
{
"message": "This is message number 2",
"message2": "This is message2 number 2"
},
{
"message": "This is message number 3",
"message2": "This is message2 number 3"
}
]
}
备选案文2:
"message": [
{
"url": "http://0.0.0.0:xxx1",
"message": "This is message number 1",
"message2": "This is message2 number 1"
},
{
"url": "http://0.0.0.0:xxx1",
"message": "This is message number 2",
"message2": "This is message2 number 2"
},
{
"url": "http://0.0.0.0:xxx1",
"message": "This is message number 2",
"message2": "This is message2 number 2"
},
{
"url": "http://0.0.0.0:xxx2",
"message": "This is message number 1",
"message2": "This is message2 number 1"
},
{
"url": "http://0.0.0.0:xxx2",
"message": "This is message number 2",
"message2": "This is message2 number 2"
},
{
"url": "http://0.0.0.0:xxx2",
"message": "This is message number 2",
"message2": "This is message2 number 2"
}
]
我可以得到每个变量(url,message,message2),但我如何将它们合并到一个像选项1或选项2的dict中?
2条答案
按热度按时间dwthyt8l1#
最简单的方法是从最接近原始数据的选项1开始。例如,您可以在您的剧本中将其声明为var:
json_query
需要community.general
集合(通常在安装了ansible meta包的情况下可用)和pip install jmespath
*这将给出(调试上述变量):
从这里开始,如果你需要在看起来像选项2的结构上循环,使用
subelements
查找很容易实现:其给出:
以下是完整测试的行动手册:
kwvwclae2#
下面的代码加载输入json,然后创建一个新数组,其结构与选项1中要求的结构相同,方法是在迭代消息列表时创建新项: