Exclude object if sub array contains n occurrences of a string with jq

寵の児 提交于 2020-05-16 05:46:11

问题


I have this

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

I want to count the occurrences of "bar" in array label then exclude object if count > 1 (can be in 2part)

ex after process:

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

I try different solutions, based on

How to select items in JQ based on value in array

and

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

but I can't achieve this!


回答1:


This seems to be working:

Keeps only the items with a label property set to an array that contains only one occurrence of the substring "bar".

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



回答2:


You can use a reduce function taking the entire JSON as input and iterate over one object at a time and add it to the final result, only if there is one occurrence

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

The part $d.label[] | select(contains("bar"))] |length returns the count within the label array how many occurrences of bar occurs. We add it to the final result . + [$d] only if the occurrence is 1 or less than 2 which you can modify as needed.

Or the now deleted answer from oguz-ismail which is equally neat and effective. Added here as a reference for future readers

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


来源:https://stackoverflow.com/questions/61079552/exclude-object-if-sub-array-contains-n-occurrences-of-a-string-with-jq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!