jsonansiblejmespathjson-query

Ansible - nested loop over object without knowing object/key name


I'm working on an ansible playbook, I need to get a value from a JSON API result. I want to get the value of the key "1h" without knowing the previous object (sd#eureka...), and i need to loops over all my results, and all my buckets.

{
  "etat_ms_rep": {
    "results": [
      {
          "buckets": {
            "sd#eureka#pixidanalyticsbackend#c3fb422bb36882d9f502092fd75fcb34": {
              "1h": -1,
              "1m": -1
            },
            "sd#eureka#pixidanalyticsbackend#348fdab155904e22ca0c744d0c052cf8": {
              "1h": 100,
              "1m": 100
            }
          }
      },
      {
          "buckets": {
            "sd#eureka#pixidorchestratorbackend#8fa3441c6c5caa2d5f0e3264a00be91b": {
              "1h": 100,
              "1m": 100
            },
            "sd#eureka#pixidorchestratorbackend#6dc48be83cb86ae1a73b344e9421ed8e": {
              "1h": 100,
              "1m": 100
            }
          }
      }
    ]
  }
}

I tried that but without success, it doesnt show the value of "1h" key...

 - name: Display all bucket info
    set_fact:
     test: "{{ etat_ms_rep.results | json_query(jmesquery) }}"
    vars:
      jmesquery: " [*].['1h'] "

Solution

  •     - debug:
            msg: "{{ etat_ms_rep.results | json_query(query) }}"
          vars:
            query: '[].*.*."1h"'
    

    gives

      msg:
      - - - -1
        - - 100
      - - - 100
        - - 100
    
        - debug:
            msg: "{{ etat_ms_rep.results | json_query(query) | flatten }}"
          vars:
            query: '[].*.*."1h"'
    

    gives

      msg:
      - -1
      - 100
      - 100
      - 100
    
        - debug:
            msg: "{{ etat_ms_rep.results | json_query(query) }}"
          vars:
            query: '[].*.*."1h"|[]|[]'
    

    Example of a complete playbook for testing

    - hosts: all
    
      vars:
    
        etat_ms_rep:
          results:
            - buckets:
                cb34: {1h: -1, 1m: -1}
                2cf8: {1h: 100, 1m: 100}
            - buckets:
                ed8e: {1h: 100, 1m: 100}
                e91b: {1h: 100, 1m: 100}
    
      tasks:
    
        - debug:
            msg: "{{ etat_ms_rep.results | json_query(query) }}"
          vars:
            query: '[].*.*."1h"'
    
        - debug:
            msg: "{{ etat_ms_rep.results | json_query(query) | flatten }}"
          vars:
            query: '[].*.*."1h"'
    
        - debug:
            msg: "{{ etat_ms_rep.results | json_query(query) }}"
          vars:
            query: '[].*.*."1h"|[]|[]'