基于字符串数组在jq中进行筛选



这接近于这个问题:jq根据列表中的值过滤JSON数组,唯一的区别是条件。我不想把平等作为一个条件,而是一个"平等";包含";,但我正在努力做到正确。

问题是:如果希望根据条目中特定值的存在来筛选输入文件的元素输入文件:

[{
"id":"type 1 is great"
},{
"id":"type 2"
},
{
"id":"this is another type 2"
},
{
"id":"type 4"
}]

筛选器文件:ids.txt:

type 2
type 1

select.jq文件:

def isin($a): . as $in | any($a[]; contains($in));
map( select( .id | contains($ids) ) )

jq命令:

jq --argjson ids "$(jq -R . ids.txt | jq -s .)" -f select.jq test.json

预期的结果应该是:

[{
"id":"type 1 is great"
},{
"id":"type 2"
},
{
"id":"this is another type 2" 
}]

问题显然在于";isin";函数,那么如何正确地编写它来检查一个条目是否包含另一个数组的字符串之一呢?

这里有一个解决方案,说明不需要多次调用jq。根据问题中所示的jq程序,它还假定选择是基于";id";钥匙

< ids.txt jq -nR --argfile json input.json '
# Is the input an acceptable value?
def acceptable($array): any(contains($array[]); .);
[inputs] as $substrings
| $json 
| map( select(.id | acceptable($substrings)) )
'

关于--argfile的注记

--argfile已被弃用,因此您可能希望使用--slurpfile,在这种情况下,您必须编写$json[0]

最新更新