'ansible, json_query - How to get data from JSON with conditions from two different levels

Hello Developer Community!

I'm currently working on developing some Ansible playbooks to manage Citrix NetScaler configuration and would like to ask for some help about the following. I have the following data structure defined:

{
"msg": [
    {
        "healthmonitor": "YES",
        "lbmonitor_binding": [
            {
                "monitor_name": "MONITOR_foo1"
            },
            {
                "monitor_name": "MONITOR_bar1"
            }
        ],
        "name": "LBSVC_foo1",
        "port": "80",
        "servername": "LBSRV_foo1",
        "servicetype": "HTTP"
    },
    {
        "healthmonitor": "YES",
        "lbmonitor_binding": [
            {
                "monitor_name": "MONITOR_foo2"
            }
        ],
        "name": "LBSVC_foo2",
        "port": "80",
        "servername": "LBSRV_foo2",
        "servicetype": "HTTP"
    },
    {
        "healthmonitor": "YES",
        "lbmonitor_binding": [
            {
                "monitor_name": "MONITOR_foo1"
            }
        ],
        "name": "LBSVC_foo3",
        "port": "80",
        "servername": "LBSRV_foo3",
        "servicetype": "HTTP"
    }
]}

I would like to get an entry from "msg" list using json_query filters:

Condition 1:

 - "name": "LBSVC_foo1"
 - "monitor_name": "MONITOR_foo1"

Expected result 1:

    {
    "healthmonitor": "YES",
    "lbmonitor_binding": [
        {
            "monitor_name": "MONITOR_foo1"
        },
        {
            "monitor_name": "MONITOR_bar1"
        }
    ],
    "name": "LBSVC_foo1",
    "port": "80",
    "servername": "LBSRV_foo1",
    "servicetype": "HTTP",
},

Condition 2:

 - "name": "LBSVC_foo3"
 - "monitor_name": "MONITOR_bar1"

Expected result 2: [Empty]

I have tried to use some JSON queries on this validator page, but they do not work, I always get empty or partial results or incorrect json_query format errors. For example:

$.msg.[?(@.name == 'LBSVC_foo1')] && lbmonitor_binding.[?(@.monitor_name == 'MONITOR_foo1')]

Could anyone please point me to the right direction, how json_query format should look like in case I have conditions defined located in two "different levels" in JSON structure ("name" and "monitor_name")? Thank You very much in advance!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source