包含的json格式查询 [英] json format query with contains
问题描述
我在ansible中有以下json输出:
I have the following json output in ansible:
[{
"active_transaction": null,
"cores": 4,
"hostname": "alpha-auth-wb01"
},
{
"active_transaction": null,
"cores": 4,
"hostname": "beta-auth-wb01"
}]
现在,我尝试过滤输出以仅显示主机名包含字母的输出.
Now I am trying to filter the output to just show the output where the hostname contains alpha for example.
输出应为:
[{
"active_transaction": null,
"cores": 4,
"hostname": "alpha-auth-wb01"
}]
代码和结果:
jq: "[?contains(hostname, 'alpha')]"
fatal: [worker.domain]: FAILED! => {"msg": "JMESPathError in json_query filter plugin:\\nIn function contains(), invalid type for value: None, expected one of: ['array', 'string'], received: \\"null\\""}
还尝试添加from_json | to_json和另一种方法.仍然失败.
Also tried adding from_json | to_json and the other way around. Still fails.
任何想法都值得赞赏!
Any ideas much appreciated!
推荐答案
正如@Matthew L Daniel提到的那样,由于引用问题,您应该将查询存储在变量中.您的查询也不正确,对于您想要的.据我了解,您想选择所有元素,其中hostname
包含字符串alpha
.完整的解决方案如下:
As @Matthew L Daniel mentioned, you should store your query in a variable, because of quoting issues. Also your query is incorrect, for what you want. As I understood, you would like to select all elements, where the hostname
contains the string alpha
. A fully working solution is the following:
---
- hosts: localhost
gather_facts: False
vars:
jq: "[?contains(hostname, 'alpha')]"
json: |
[{
"active_transaction": null,
"cores": 4,
"hostname": "alpha-auth-wb01"
},
{
"active_transaction": null,
"cores": 4,
"hostname": "beta-auth-wb01"
}]
tasks:
- name: DEBUG
debug:
msg: "{{ json | from_json | json_query(jq) }}"
如果您不想在变量中编写json_query
,则可以这样引用:
If you don't want to write your json_query
in a var you could quote it like this:
"{{ json | json_query(\"[?contains(hostname, 'alpha')]\") }}"
但是我建议将其放入变量中.
But I would recommend, to put it in a var.
这篇关于包含的json格式查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!