using jsonpath-plus to filter the value

810 views Asked by At

Json is

{
    "value": [
    {
        "resourceType": "virtualMachines",
        "name": "Standard_B1ms",
        "capabilities": [
            {
                "name": "MemoryGB",
                "value": "6"
            },
            {
                "name": "vCPUs",
                "value": "5"
            }
        ]
    },
    {
        "resourceType": "virtualMachines",
        "name": "Standard_B1s",
        "tier": "Standard",
        "size": "B1s",
        "family": "standardBSFamily",
        "capabilities": [
            {
                "name": "MemoryGB",
                "value": "2"
            },
            {
                "name": "vCPUs",
                "value": "1"
            }
        ]
    }]
}

I want only those names(eg.Standard_B1ms) which has vCPUs >=2 and MemoryGB >=4 in capabilities. I am unable to do that using regular jsonpath, so i tried using jsonpath-plus but my attempt was unsuccessful.

1

There are 1 answers

0
wp78de On

It can be done using the ^ parent node operator available in JsonPath-Plus. The idea is to go up after searching and then descend again to search the array again as required. Depending on your needs yo can go up one or more nodes and grab or search the values as needed. Unfortunately, the syntax is a bit cumbersome but this worked for me:

$.value[*].capabilities[?(@.name === 'MemoryGB' && @.value >=4)]^^^[*][?(@.name === 'vCPUs' && @.value >=4)]^^^

It might be better and easier to split the task into two steps, e.g. filter for 4+ memory first:

$.value[*].capabilities[?(@.name === 'MemoryGB' && @.value >=4)]^^^

and then filter the result for vCPUs:

$.[*][?(@.name === 'vCPUs' && @.value >=4)]^^^