简体   繁体   中英

Using jq find key/value pair based on another key/value pair

I'm pasting here a JSON example data which would require some manipulation to get a desired output which is mentioned in the next section to be read after this piece of JSON code.

I want to use jq for parsing my desired data.

{
"MetricAlarms": [
    {
        "EvaluationPeriods": 3,
        "ComparisonOperator": "GreaterThanOrEqualToThreshold",
        "AlarmActions": [
            "Unimportant:Random:alarm:ELK2[10.1.1.2]-Root-Disk-Alert"
        ],
        "AlarmName": "Unimportant:Random:alarm:ELK1[10.1.1.0]-Root-Alert",
        "Dimensions": [
            {
                "Name": "path",
                "Value": "/"
            },
            {
                "Name": "InstanceType",
                "Value": "m5.2xlarge"
            },
            {
                "Name": "fstype",
                "Value": "ext4"
            }
        ],
        "DatapointsToAlarm": 3,
        "MetricName": "disk_used_percent"
    },
    {
        "EvaluationPeriods": 3,
        "ComparisonOperator": "GreaterThanOrEqualToThreshold",
        "AlarmActions": [
            "Unimportant:Random:alarm:ELK2[10.1.1.2]"
        ],
        "AlarmName": "Unimportant:Random:alarm:ELK2[10.1.1.2]",
        "Dimensions": [
            {
                "Name": "path",
                "Value": "/"
            },
            {
                "Name": "InstanceType",
                "Value": "r5.2xlarge"
            },
            {
                "Name": "fstype",
                "Value": "ext4"
            }
        ],
        "DatapointsToAlarm": 3,
        "MetricName": "disk_used_percent"
    }
]
}

So when I Pass some Key1 & value1 as a parameter "Name": "InstanceType", to the JQ probably using cat | jq and output expected should be as below

m5.2xlarge
r5.2xlarge

A generic approach to search for a key-value pair ( sk - sv ) in input recursively and extract another key's value ( pv ) from objects found:

jq -r --arg sk Name         \
      --arg sv InstanceType \
      --arg pv Value        \
'.. | objects | select(contains({($sk): $sv})) | .[$pv]' file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM