Search code examples
ansiblejson-query

Ansible json_query to filter data on dict of list of dict


I have an Ansible task which collects users data based on certain condition and registers the out to a variable and trying to iterate the registered data in the next task to just get the name parameter alone.

{
    "registered_data": {
        "changed": false,
        "msg": "All items completed",
        "results": [
          {
            "ansible_loop_var": "item",
            "changed": false,
            "failed": false,
            "data_details": [
              {
                "name": "John",
                "street": "SanFisco"
              },
              {
                "name": "Dan",
                "street": "Califor"
              },
              {
                "name": "Jack",
                "street": "NY"
              },
              {
                "name": "Wills",
                "street": "NJ"
              }
            ],
            "invocation": {
              "module_args": {
                "sort_by": null,
                "sort_order": null
                }
            },
            "item": {
              "status": "READY"
            }
          },
          {
            "ansible_loop_var": "item",
            "changed": false,
            "failed": false,
            "data_details": [],
            "invocation": {
              "module_args": {
                "sort_by": null,
                "sort_order": null
              }
            },
            "item": {
              "status": "READY"
            }
          },
          {
            "ansible_loop_var": "item",
            "changed": false,
            "failed": false,
            "data_details": [],
            "invocation": {
              "module_args": {
                "sort_by": null,
                "sort_order": null
              }
            },
            "item": {
              "status": "READY"
            }
          }
        ]
      }
}

Am trying to use the below ansible task to parse & filter the data which doesn't return any output.

- name: 'printing data'
  delegate_to: 'localhost'
  when: item
  loop: "{{ registered_data |json_query(projection_query) }}"
  debug:
    msg: "{{ item }}"
  vars:
    projection_query: "results.[*].name"

Solution

  • The task below

        - debug:
            msg: "{{ registered_data.results|json_query(query) }}"
          vars:
            query: "[].data_details[].name"
    

    gives

      msg:
      - John
      - Dan
      - Jack
      - Wills