JQ:获取元素ID(如果包含密钥)

时间:2019-01-08 20:51:22

标签: json select key extract jq

我正在尝试获取“参数”中具有“默认”键的元素的列表:

{
"Parameters" : {
    "Ecosystem": {
        "Type": "String",
        "Description": "Ecosystem to deploy the resources in to",
        "MinLength": "1"
    },
    "InstanceTenancy": {
        "Type": "String",
        "Description": "EC2 Instance Tenancy",
        "Default": "default",
        "AllowedValues": [
            "default", "dedicated"
        ]
    },
    "InstanceSecurityGroups": {
        "Type": "List<AWS::EC2::SecurityGroup::Id>",
        "Description": "EC2 Instance Security Groups",
        "MinLength": "1"
    },
    "InstanceAmi": {
        "Type": "AWS::EC2::Image::Id",
        "Description": "AMI to deploy to the EC2 instances",
        "Default": "ami-11223344"
    }
}

}

我最近得到的是jq '.Parameters | map_values(has("Default"))'

{
  "Ecosystem": false,
  "InstanceTenancy": true,
  "InstanceSecurityGroups": false,
  "InstanceAmi": true
}

有没有办法我可以获取与此过滤器匹配的键列表?例如

"InstanceTenancy"
"InstanceAmi"

1 个答案:

答案 0 :(得分:0)

使用to_entries可以从根本上解决问题:

.Parameters
| to_entries[]
| select(.value | has("Default"))
| .key

但是您的方法也可以起作用:

.Parameters
| map_values(has("Default"))
| keys_unsorted[] as $k
| select(.[$k])
| $k