简体   繁体   English

使用 Ansible json_query 中的项目

[英]Using item in Ansible json_query

I'm trying to loop through a list of keys to grab associated names from some json:我正在尝试遍历键列表以从某些 json 中获取关联名称:

- name: show names
  debug:
    msg: "{{ data.json | json_query(query) }}"
  vars:
    query: "[? key==item].name"
  with_items: "{{ keys.split() }}"

But it never displays properly when I try to run it.但是当我尝试运行它时它永远不会正确显示。 The keys are correct, but no data is returned:键是正确的,但没有返回数据:

TASK [get_help_on_SO: show] 
ok: [localhost] => (item=Key1) => {
    "msg": []
}
ok: [localhost] => (item=Key2) => {
    "msg": []
}

Manually putting in the code works just fine so my query syntax seems to be right:手动输入代码就可以了,所以我的查询语法似乎是正确的:

query: "[? key==`Key1`].name"

TASK [get_help_on_SO : show] 
ok: [localhost] => (item=Key1) => {
    "msg": [
        "FooBar 1"
]
}
ok: [localhost] => (item=Key2) => {
    "msg": [
        "FooBar 1"
    ]
}

How can I properly pass the item into the json_query ?如何正确地将item传递到json_query

You didn't surround the item variable with any Jinja delimiters, so it is not interpreted.您没有用任何 Jinja 分隔符包围item变量,因此它不会被解释。
You end testing if the key is equal to the string 'item' and not to the string stored in the variable item .如果key等于字符串'item'而不是存储在变量item中的字符串,则结束测试。

- name: show names
  debug:
    msg: "{{ data.json | json_query(query) }}"
  vars:
    query: "[?key==`{{ item }}`].name"
  with_items: "{{ keys.split() }}"

Given the data鉴于数据

    keys: 'key1 key3'
    data:
      json: [{
            "key": "key1",
            "name": "name1"
            },
            {
            "key": "key2",
            "name": "name2"
            },
            {
            "key": "key3",
            "name": "name3"
            }
            ]

the expected result is预期的结果是

  - name1
  - name3

It's possible to avoid both the loop and json_query and simplify the solution.可以避免循环json_query并简化解决方案。 The task below下面的任务

    - name: show names
      debug:
        msg: "{{ data.json|
                 selectattr('key', 'in', my_keys)|
                 map(attribute='name')|
                 list }}"
      vars:
        my_keys: "{{ keys.split() }}"

gives

  msg:
  - name1
  - name3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM