问题
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