【问题标题】:Exclude object if sub array contains n occurrences of a string with jq如果子数组包含 n 次出现的带有 jq 的字符串,则排除对象
【发布时间】:2020-04-07 11:59:25
【问题描述】:

我有这个

[
  {
    "title": "foo",
    "label": [
      "bar-one",
      "bare-two"
    ]
  },
  {
    "title": "foo_42",
    "label": [
      "bar-one",
      "bare-two"
    ]
  },
  {
    "title": "foo_42",
    "label": [
      "bar-one"
    ]
  }
]

我想计算数组标签中“bar”的出现次数 如果 count > 1 则排除对象(可以在 2part 中)

处理后的前:

[
  {
    "title": "foo_42",
    "label": [
      "bar-one"
    ]
  }
]

我尝试了不同的解决方案,基于

How to select items in JQ based on value in array

https://github.com/stedolan/jq/issues/861

但我做不到!

【问题讨论】:

    标签: json jq


    【解决方案1】:

    这似乎有效:

    仅保留将具有label 属性的项目设置为仅包含一次出现的子字符串“bar”的数组。

    map(select(.label | map(select(contains("bar"))) | length <= 1))
    

    【讨论】:

      【解决方案2】:

      您可以使用reduce函数将整个JSON作为输入并一次迭代一个对象并将其添加到最终结果中,前提是只有一次出现

      jq -n '
          reduce inputs[] as $d (. ;
              if [ $d.label[] | select(contains("bar")) ] | length == 1 then
                  . + [$d]
              else
                  empty
              end
           )' \
      json
      

      $d.label[] | select(contains("bar"))] |length 部分返回label 数组中出现bar 的次数。仅当出现次数为 1 或小于 2 时,我们才会将其添加到最终结果 . + [$d],您可以根据需要进行修改。

      或者来自oguz-ismail 的现已删除的答案,同样简洁有效。此处添加为未来读者的参考

      jq ' 
         map(
           select(.label |
             any(., map(select(index("bar"))); length < 2)
           )
      )' json
      

      【讨论】:

        猜你喜欢
        • 2018-04-02
        • 2021-08-10
        • 2022-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多