3

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 ([])?

2 Answers 2

4

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]).

Sign up to request clarification or add additional context in comments.

Comments

4

You can add ansible filter first, like so:

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

It'll return scalar value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.