【问题标题】:Filter in jq based on an array of string根据字符串数组在jq中过滤
【发布时间】:2021-06-23 11:10:12
【问题描述】:

这与这个问题很接近:jq filter JSON array based on value in list,唯一的区别是条件。我不希望平等作为条件,而是“包含”,但我正在努力正确地做到这一点。

问题: 如果要根据条目中是否存在特定值来过滤输入文件的元素 输入文件:

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

问题显然出在select.jq文件的“isin”函数中,那么如何正确编写来检查一个条目是否包含另一个数组的字符串之一?

【问题讨论】:

    标签: json object select substring jq


    【解决方案1】:

    这是一个说明不需要多次调用 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]

    【讨论】:

    • 我认为反对使用--argfile 的警告是过分的。当输入是 JSON 文件时,使用 --argfile 非常有意义,就像这里的情况一样。当文件是 JSON 文本序列时不要使用它,你很好。 tl;博士:--argfile 用于 JSON 文本。 --slurpfile 用于 JSON 文本。
    • @ikegami - 我同意,但对于那些可能不知道的人来说,它被弃用是有原因的:它有时表现得像 --slurpfile。也许将来它会忽略除第一个 JSON 实体以外的所有实体 ....
    猜你喜欢
    • 2017-06-29
    • 2020-08-15
    • 2012-12-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2013-11-25
    相关资源
    最近更新 更多