donald.sys
donald.sys

Reputation: 301

How to just output the correct result with key and value?

I have a json as below:

[
    {
      "AvailabilityZone": "ap-northeast-1a",
      "Tags": [
        {
          "Value": "value1",
          "Key": "key1"
        },
        {
          "Value": "value2",
          "Key": "key2"
        }
      ],
    },
    {
          "AvailabilityZone": "ap-northeast-1a",
          "Tags": [
            {
              "Value": "value3",
              "Key": "key3"
            },
            {
              "Value": "value4",
              "Key": "key4"
            }
          ],
        },
]

when i input key and value from keyboard. I want to just output the correct result with the key and value through the jq option.

Example: I input Key:value is key3:value3. My desire:

{
      "AvailabilityZone": "ap-northeast-1a",
      "Tags": [
        {
          "Value": "value3",
          "Key": "key3"
        },
        {
          "Value": "value4",
          "Key": "key4"
        }
      ],
}

Upvotes: 0

Views: 86

Answers (2)

choroba
choroba

Reputation: 241758

Use select to filter the array under Tags:

jq '.[].Tags | select((.[].Key == "key3") and (.[].Value="value3"))  ' < file.json

Together with reading the key and value from the stdin:

echo key3 value3 | (
    read key value
    k=$key v=$value jq ".[].Tags
        | select((.[].Key == env.k) and (.[].Value=env.v))
    " < file.json)

Upvotes: 1

Parvez Kazi
Parvez Kazi

Reputation: 775

Seems you are using aws cli to fetch ebs volume details, you can use the filters properties of aws cli to filter out results of your query.
Here you can use below :
aws ec2 describe-volumes --filters Name=tag-key,Values="key3" Name=tag-value,Values="value3"

Find more help at:
aws ec2 describe-volumes help

I think this will be easier than filtering using jq.

Upvotes: 1

Related Questions