【问题标题】:Get values from only the related parents when matching a child匹配孩子时仅从相关父母那里获取值
【发布时间】:2019-09-21 16:13:45
【问题描述】:

我试图通过匹配子数组中的值来从数组中获取值,但我尝试的所有操作要么不返回任何内容,要么返回父数组的所有成员。我只想要孩子匹配的父母的信息。

具体来说,我想列出所有包含端口 22 规则的 AWS 安全组。

这是我尝试解析的 aws 命令行的简化示例输出:

{
    "SecurityGroups": [
        {
            "Description": "ssh and web group",
            "IpPermissions": [
                {
                    "FromPort": 22,
                    "ToPort": 22
                },
                {
                    "FromPort": 80,
                    "ToPort": 80
                }
            ],
            "GroupName": "ssh-web",
            "GroupId": "sg-11111111"
        },
        {
            "Description": "https group",
            "IpPermissions": [
                {
                    "FromPort": 443,
                    "ToPort": 443
                },
                {
                    "FromPort": 8443,
                    "ToPort": 8443
                }
            ],
            "GroupName": "https",
            "GroupId": "sg-22222222"
        }
    ]
}

我试过这个:

aws ec2 describe-security-groups |
    jq '.SecurityGroups[] as $top |
        .SecurityGroups[].IpPermissions[] |
        select(.FromPort == 22) |
        $top'

还有这个:

aws ec2 describe-security-groups |
    jq '. as $top |
        .SecurityGroups[].IpPermissions[] |
        select(.FromPort == 22) |
        $top'

这两个命令都显示了两个顶级数组条目,而不是只显示一个包含端口 22 条目;它们只显示 aws 命令的全部输出。

下面回答这个问题的人具体指的是我实际遇到的潜在范围界定问题,但他对如何处理它的简要描述不足以让我理解:

jq - How do I print a parent value of an object when I am already deep into the object's children?

我想看看这个:

GroupName: "https"
GroupID: "sg-22222222"

我不认为我完全理解使用 'as' 的工作原理,这可能是我的绊脚石。

【问题讨论】:

  • 我应该更加小心地接受这些编辑。他们搞砸了格式。

标签: json jq


【解决方案1】:

如果你需要父母,不要堕落为孩子。

.SecurityGroups[]
| select(any(.IpPermissions[]; .FromPort == 22))
| .GroupName, .GroupId

应该可以。

【讨论】:

  • 这绝对有效!谢谢!我仍在努力思考“任何”的使用以及生成器是什么。
  • 现在我看到了下降的错误,有理由不这样做吗? jq -r '.SecurityGroups[] | select(.IpPermissions[].FromPort == 22) | .GroupName, .GroupId'
  • @bchill 不是很明显吗? .IpPermissions[]生成端口规则流,如果其中任何包含FromPort: 22,则选择父级。
  • @bchill 是的。如果有两个端口规则包含FromPort: 22,则选择父级两次。
  • 啊。知道了。我能够产生一个多余结果的例子。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-31
  • 1970-01-01
  • 1970-01-01
  • 2018-09-22
  • 1970-01-01
相关资源
最近更新 更多