ansiblejmespathjson-query

Does JMESPath have an 'in' like operator, that will be true if a key's value is present in an array of strings?


Does JMESPath have an 'in' like operator, that will be true if a key's value is present in an array of strings?

Given the following snippet of data, (assume the number of items is much larger, and I want to select a few)

[
  {
    "object": {
      "metadata": {
        "name": "item1"
      }
    },
    "data": {}
  },
  {
    "object": {
      "metadata": {
        "name": "item2"
      }
    },
    "data": {}
  },
  {
    "object": {
      "metadata": {
        "name": "item3"
      }
    },
    "data": {}
  }
]

Is there something that would allow me to select any object, whose metadata.name key's value is in the list ['item1', 'item2']?


Solution

  • Q: "Select any object, whose metadata.name key's value is in the list ['item1', 'item2']"

    A: Use the JmesPath built-in function contains. The below query does what you want

    [?contains(['item1', 'item2'], object.metadata.name)]
    

    • Example of a complete playbook for testing
    - hosts: localhost
    
      vars:
    
        data:
          - data: {}
            object:
              metadata:
                name: item1
          - data: {}
            object:
              metadata:
                name: item2
          - data: {}
            object:
              metadata:
                name: item3
    
        result: "{{ data|json_query(result_query) }}"
        result_query: |
          [?contains(['item1', 'item2'], object.metadata.name)]
    
      tasks:
    
        - debug:
            var: result
    

    gives (abridged)

      result:
      - data: {}
        object:
          metadata:
            name: item1
      - data: {}
        object:
          metadata:
            name: item2
    
    • You can put the list into a variable. For example,
        result: "{{ data|json_query(result_query) }}"
        filter: ['item1', 'item2']
        result_query: |
          [?contains({{ filter }}, object.metadata.name)]