json 格式查询包含

json format query with contains

我在 ansible 中有以下 json 输出:

[{
    "active_transaction": null,
    "cores": 4,
    "hostname": "alpha-auth-wb01"
},
{
    "active_transaction": null,
    "cores": 4,
    "hostname": "beta-auth-wb01"
}]

现在我正在尝试过滤输出以仅显示主机名包含 alpha 的输出。

输出应该是:

[{
    "active_transaction": null,
    "cores": 4,
    "hostname": "alpha-auth-wb01"
}]

代码和结果:

Ansible code

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 反之亦然。仍然失败。

非常感谢任何想法!

正如@Matthew L Daniel 提到的,由于引用问题,您应该将查询存储在变量中。您的查询也不正确,您想要什么。据我了解,您想要 select 所有元素,其中 hostname 包含字符串 alpha。一个完全有效的解决方案如下:

---
- 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 写在 var 中,您可以这样引用它:

"{{ json | json_query(\"[?contains(hostname, 'alpha')]\") }}"

但我建议将它放在一个变量中。

感谢您的所有回答。

我犯了一个错误,对错误的变量使用了查询。呸!

在 vsdetails 上使用建议的 json_query var 非常有效。谢谢! :)