JQ:当bash数组中存在属性值时选择 [英] JQ: Select when attribute value exists in a bash array
问题描述
我正在使用jq 1.4.
当我的$selected_subnets
(bash变量)中存在VPCZoneIdentifier时,我试图选择元素.
I'm using jq 1.4.
I trying to select elements when VPCZoneIdentifier exists in my $selected_subnets
(bash variable).
selected_subnets="valueA valueB"
input='{"elements":[
{"name": "nameA", "VPCZoneIdentifier": "valueA"},
{"name": "nameB", "VPCZoneIdentifier": "valueB"},
{"name": "nameC", "VPCZoneIdentifier": "valueC"}
]}'
test
和match
fn仅在v1.5上可用.
test
and match
fn are only available on v1.5.
推荐答案
这有些棘手,但是可以使用reduce
完成.整个过程看起来像这样:
This is a little tricky, but it can be done with reduce
. The whole thing could look like this:
selected_subnets_json=$(echo "\"$selected_subnets\"" | jq -c -M 'split(" ")')
echo "$input" | jq -M '.elements = [.elements[] | select(.VPCZoneIdentifier as $id | '"$selected_subnets_json"' | reduce .[] as $v (false; . or $id == $v))]'
第一部分从shell列表中创建一个JSON数组:
The first part makes a JSON array from the shell list:
$ echo "\"$selected_subnets\"" | jq -c -M 'split(" ")'
["valueA","valueB"]
第二部分使用reduce
过滤器将.VPCZoneIdentifier
属性与该数组的所有元素进行比较.将selected_subnets_json
变量扩展到其中后,过滤器如下所示:
The second part uses the reduce
filter to compare the .VPCZoneIdentifier
property with all elements of this array. With the selected_subnets_json
variable expanded into it, the filter looks as follows:
.elements = [
.elements[] |
select(.VPCZoneIdentifier as $id |
[ "valueA", "valueB" ] | reduce .[] as $v (false; . or $id == $v))
]
也就是说,elements
属性会被与选择标准相匹配的那些元素覆盖
That is to say, the elements
property is overwritten with those elements of it that match the selection criterium
.VPCZoneIdentifier as $id | [ "valueA", "valueB" ] | reduce .[] as $v (false; . or $id == $v))
其中的第一部分将VPCZoneIdentifier
记为$id
(因为.
不久后将意味着完全不同),并且
Of this the first part remembers the VPCZoneIdentifier
as $id
(because .
will shortly mean something entirely different), and
[ "valueA", "valueB" ] | reduce .[] as $v (false; . or $id == $v))
是子网阵列的或减.在这种情况下,它会扩展为false or $id == "valueA" or $id == "valueB"
.
is an or-reduction of the subnet array. It expands to false or $id == "valueA" or $id == "valueB"
in this case.
如果您想一口气拥有它,可以写
If you prefer to have it all in one go, you could write
echo "$input" | jq -M '.elements = [.elements[] | select(.VPCZoneIdentifier as $id | ("'"$selected_subnets"'" | split(" ")) | reduce .[] as $v (false; . or $id == $v))]'
除以内联方式完成$selected_subnets
的拆分外,此方法的工作原理基本相同.
This works essentially the same way, except the splitting of $selected_subnets
is done inline.
这篇关于JQ:当bash数组中存在属性值时选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!