根据子数组的值删除json数组元素 [英] Delete json array elements based on values of subarray
问题描述
我有以下包含此数组结构的json文件:
I have the following json file which contains this array structure:
{
"outer": [
{
"inner": [
{
"value": "val1"
},
{
"value": "val3"
}
]
},
{
"inner": [
{
"value": "val2"
},
{
"value": "val1"
}
]
},
{
"inner": [
{
"value": "val2"
},
{
"value": "val1"
},
{
"value": "val3"
}
]
}
]
}
我想从 outer
数组中删除 inner
数组,该数组的元素具有特定的值并且具有一定的长度.例如,如果我要删除包含值"val1"
和"val2"
的 inner
数组,则结果应为:
I want to delete the inner
array from the outer
array whose elements have specific values and and is of certain length. E.g., if I want to delete the inner
array which contains values "val1"
and "val2"
the result should be:
{
"outer": [
{
"inner": [
{
"value": "val1"
},
{
"value": "val3"
}
]
},
{
"inner": [
{
"value": "val2"
},
{
"value": "val1"
},
{
"value": "val3"
}
]
}
]
}
我尝试过
jq 'del( .outer[]|select(.inner[0].value == "val1"))'
但是我不知道如何检查第二个条件,长度以及最上面的值可能以任何顺序出现.
but I do not know how to check for the second condition, the length and on top of that the values may appear in any order.
推荐答案
您要查找的 jq
过滤器是:
del(.outer[] | select(.inner | map(.value) | sort == ["val1", "val2"]))
.inner |map(.value)
产生一个数组,该数组包含 .inner
所包含的所有对象中与 value
键相关的值.
.inner | map(.value)
produces an array that contains the values associated to the value
key from all objects contained by .inner
.
sort
是因为 ==
对数组进行了一对一的比较.这样,无论它们的顺序如何,它都匹配 .inner
中包含的对象.当然,您必须在右侧使用排序后的数组(即 ["val1","val2"]
而不是 ["val2","val1"] 代码>).
sort
is needed because ==
does a one-to-one comparison of arrays. This way it matches the objects contained in .inner
no matter their order. Of course, you have to use a sorted array on the right-hand side (i.e. ["val1", "val2"]
and not ["val2", "val1"]
).
在操作中看到它.
这篇关于根据子数组的值删除json数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!