json format query with contains

10,301

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.

Share:
10,301
Admin
Author by

Admin

Updated on June 18, 2022

Comments

  • Admin
    Admin almost 2 years

    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!

    • nwinkler
      nwinkler over 5 years
      What do you get as a result when you run the query from your question?
    • mdaniel
      mdaniel over 5 years
      if it's as written, it's because you have a single quoted string in a single quoted string, and thus I'm surprised it doesn't explode at jinja time with an unresolved variable; you'll be happier pulling that out into a vars: jq: "[?contains(@, 'alpha') == `true`]" and then {{ json | json_query(jq) }}
    • Admin
      Admin over 5 years
      Thanks for the answer. I've edited my question above with the results. Still fails.
  • Admin
    Admin over 5 years
    Thanks for the in-depth answer. I've edited my question above with the results. Still fails.
  • JGK
    JGK over 5 years
    Well, the solution works. How is your JSON defined in ansible? Please post your complete playbook. Where is the difference to my solution?