ruud
ruud

Reputation: 21

JQ: Getting element id if it contains a key

I am trying to get a list of elements in "Parameters" that have a "Default" key:

{
"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"
    }
}

}

The closest I am getting is jq '.Parameters | map_values(has("Default"))'

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

Is there a way I can get just a list of keys which match this filter? e.g.

"InstanceTenancy"
"InstanceAmi"

Upvotes: 1

Views: 311

Answers (1)

peak
peak

Reputation: 116919

Using to_entries allows a fundamentally simple solution:

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

But your approach can also be made to work:

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

Upvotes: 1

Related Questions