2017-09-24 63 views
1

我在OSX上运行asible 2.4.0。 下面的剧本......当使用过滤器表达式时,Ansible json_query输出列表

--- 
- 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\") }}" 

产生以下输出:

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 

我的问题是,为什么在第二调试任务列表中([])的输出?

回答

1

这是因为在JMESPath中,这是implementation behind json_query,索引表达式定义为始终返回单个值,可能为nullsee [1])。

虽然对于过滤器表达式(投影),假设在评估查询的LHS后返回一个数组,如果没有值匹配(see: [2]),该数组可能为空。