在我的 Ansible 剧本中,我需要提取得分最低(即 7)的名称(本例中为 cory)。
如何使用给定的字典列表来执行此操作?
[
{
"name": "james",
"score": "48"
},
{
"name": "darcy",
"score": "37"
},
{
"name": "cory",
"score": "7"
}
]
答案1
数据来自哪里?如果你能确保“分数”以 int 而不是字符串的形式出现,那么这应该相当容易。
- hosts: localhost
gather_facts: no
vars:
data: [ { "name": "james", "score": 48 }, { "name": "darcy", "score": 37 }, { "name": "cory", "score": 7 } ]
tasks:
- debug:
msg: "{{ (data |sort(attribute='score'))[0]['name'] }}"
# TASK [debug] *******
# ok: [localhost] => {
# "msg": "cory"
# }