Find values in JSON with Ansible without knowing where it is

Viewed 51

I am trying to find a way to parse below json and get the list of city for all items with "type": "location". The challenge is I don't always know the key names such as us, john and location1 and location2 in the example below. I have tried to use json_query and regex_search without success.

{
    "client": {
        "us": {
            "john": {
                "job": {
                    "type": "job",
                    "job": "waiter"
                },
                "location1": {
                    "type": "location",
                    "address": {
                        "street": "Main St",
                        "city": "Seattle"
                    }
                },                
                "location2": {
                    "type": "location",
                    "address": {
                        "street": "2nd ave",
                        "city": "New York"
                    }
                }
            }
        }
    }
}
1 Answers

Given the variable my_data the task below

    - debug:
        msg: "{{ my_data|
                 json_query(query1)|
                 flatten|
                 json_query(query2)
                 }}"
      vars:
        query1: "*.*.*.*"
        query2: "[?type=='location'].address.city"

gives the list

    "msg": [
        "Seattle",
        "New York"
    ]

Very probably the queries can be concatenated.

Related