DrStrangepork
DrStrangepork

Reputation: 3134

Using jq, select multiple keys and return them in an array

Given this array:

[{"Key":"base_ami","Value":"ami-46d003ac"},
{"Key":"app","Value":"amibuild"},
{"Key":"sbu","Value":"IT"},
{"Key":"base_ami_image_location","Value":"123456789012/amazon-linux"},
{"Key":"app_env","Value":"dev"},
{"Key":"Name","Value":"amazon-linux"},
{"Key":"jenkins_build_id","Value":"24"},
{"Key":"os_type","Value":"linux"},
{"Key":"version","Value":"1.0.24"}]

I want this output:

[{"Key":"app","Value":"amibuild"},{"Key":"sbu","Value":"IT"},{"Key":"app_env","Value":"dev"}]

I've got it down as far as this:

.[] | select(.Key == "app"), select(.Key == "app_env"), select(.Key == "sbu")

but that results in:

{"Key":"app","Value":"amibuild"}
{"Key":"sbu","Value":"IT"}
{"Key":"app_env","Value":"dev"}

I need those individual objects returned as elements of an array.

Upvotes: 1

Views: 5747

Answers (2)

luckman212
luckman212

Reputation: 802

Small improvement on @chepner's answer that's a bit more concise:

map(select(.Key == ("app", "app_env", "sbu")))

Upvotes: 1

chepner
chepner

Reputation: 531225

You just need to wrap the result in [...]:

[.[] | select(.Key == "app"), select(.Key == "app_env"), select(.Key == "sbu")]

You can also shorten this filter slightly:

[.[] | select(.Key == "app" or .Key == "app_env" or .Key == "sbu")]

Or use the map function:

map(select(.Key == "app" or .Key == "app_env" or .Key == "sbu"))

Upvotes: 5

Related Questions