如何使用 JQ 解析 json 响应

How to parse json response using JQ

我需要抓取目标组,并且基本侦听器已打开,以便我可以将其存储在变量中并对该目标组执行运行状况检查。这就是我正在做的事情:-

aws elbv2 --region us-east-1 describe-rules '--listener-arn=************'
{
    "Rules": [
        {
            "Priority": "1", 
            "Conditions": [
                {
                    "Field": "host-header", 
                    "HostHeaderConfig": {
                        "Values": [
                            "****"
                        ]
                    }, 
                    "Values": [
                        "****"
                    ]
                }
            ], 
            "RuleArn": "xyz", 
            "IsDefault": false, 
            "Actions": [
                {
                    "TargetGroupArn": "****", 
                    "Type": "forward"
                }
            ]
        }, 
        {
            "Priority": "default", 
            "Conditions": [], 
            "RuleArn": "abc", 
            "IsDefault": true, 
            "Actions": [
                {
                    "TargetGroupArn": "***", 
                    "Type": "forward", 
                    "Order": 1
                }
            ]
        }
    ]
}

现在我必须为 "RuleArn" 提取 TargetGroupArn 的值:"xyz" 这意味着我需要获取该目标组 arn 以便我可以在下一个命令中使用它,例如 :-

aws elbv2 --region us-east-1 describe-target-health --target-group-arn=***

一旦我 运行 这我将得到健康目标的 json 输出,我需要进一步查询一些 if 和 else 条件。我如何让 jq 解析初始 json 以获取目标组 arn 如上所述,以便我可以将其用于我未来的命令。请注意,"RuleArn" 的 TargetGroupArn 值:"xyz" 在我们的案例中不是恒定的,因为它们不断从一个目标组切换到另一个目标组。

您可以使用

var res = JSON.parse(response);

获取要解析为 Json 的响应字符串。

您可以通过两种方式实现。第一种是通过 --query 参数使用 AWS CLI 内置的 JMES 路径。

aws elbv2 --region us-west-2 describe-rules \
    '--listener-arn=************' \
    --query "Rules[?RuleArn == 'xyz'].Actions[0].TargetGroupArn" --output text

秒是要用jq

aws elbv2 --region us-west-2 describe-rules \
    '--listener-arn=************'' \
    --output json | jq -r '.Rules[]|select(.RuleArn == "xyz")| .Actions[0].TargetGroupArn'

要使用 jq 获取 TargetGroupArn,您可以使用以下 filter

aws elbv2 \
  --region us-east-1 \
  describe-rules \
  --listener-arn="************" \
  | jq ".Rules[].Actions[].TargetGroupArn"

另一种方法是使用 --query option of the aws cli.