简体   繁体   中英

How to filter key and value using jq filter in bash

After running the following command

aws ec2 describe-tags --filter "Name=resource-id,Values=i-8dh7435490fjksfd"

I have the following JSON output

{
    "Tags": [
        {
            "ResourceType": "instance", 
            "ResourceId": "i-8dh7435490fjksfd", 
            "Value": "production", 
            "Key": "Environment"
        }, 
        {
            "ResourceType": "instance", 
            "ResourceId": "i-8dh7435490fjksfd", 
            "Value": "webserver", 
            "Key": "Application"
        }
    ]
}

How do i get the following output using jq filter

Application : webserver

不使用jq解决方案

aws ec2 describe-tags   --filter "Name=resource-id,Values=i-8dh7435490fjksfd" --query 'Tags[?Key==`Application`].Value[]' --output text
.Tags[]
| select(.Key == "Application")
| "\(.Key) : \(.Value)"

You can get it in this way with using jq. Putting parentheses around the key means it will be evaluated as an expression.

cat example.json | jq '.[] | {(.[].Key): (.[].Value)}'

Output:

{
  "Environment": "production"
}
{
  "Environment": "webserver"
}
{
  "Application": "production"
}
{
  "Application": "webserver"
}

Ref: https://stedolan.github.io/jq/manual/

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