JQ:当bash数组中存在属性值时选择 [英] JQ: Select when attribute value exists in a bash array

查看:90
本文介绍了JQ:当bash数组中存在属性值时选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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"}
       ]}'

testmatch 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆