Search code examples
ansiblejmespath

Ansible json_query outputs list when using a filter expression


I'm running ansible 2.4.0 on OSX. The following playbook...

---
- hosts: localhost
  connection: local
  gather_facts: False

  vars:
    data:
    - name: thing1
      desc: I am thing 1
    - name: thing2
      desc: I am thing 2

  tasks:
  - debug: msg="{{ data|json_query(\"[1].desc\") }}"
  - debug: msg="{{ data|json_query(\"[?name=='thing2'].desc\") }}"

Produces the following output:

PLAY [localhost] ***************************************************************

TASK [debug] *******************************************************************
ok: [localhost] => {
    "msg": "I am thing 2"
}

TASK [debug] *******************************************************************
ok: [localhost] => {
    "msg": [
        "I am thing 2"
    ]
}

PLAY RECAP *********************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0

My question is, why, in the second debug task is the output in a list ([])?


Solution

  • That's because in JMESPath, which is the implementation behind json_query, an index expression is defined to always return a single value, possibly null (see [1]).

    While for the filter expression, which is a projection, an array is assumed to be returned after evaluating the LHS of your query, which may be empty in case no values are matched (see: [2]).