json format query with contains

别来无恙 提交于 2019-12-11 18:15:03

问题


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.

Output should be:

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

Code and results:

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

Also tried adding from_json | to_json and the other way around. Still fails.

Any ideas much appreciated!


回答1:


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

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.




回答2:


Thanks for all your answers.

I made a mistake and was using the query on the wrong variable. Doh!

Using the proposed json_query var on vsdetails worked like a charm. Thanks! :)



来源:https://stackoverflow.com/questions/53615369/json-format-query-with-contains

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!