![](/img/trans.png)
[英]How to filter array of objects by element property values and select the first element, using jq?
[英]How to filter array of objects by element property values using jq?
我喜欢使用jq过滤json文件:
jq . some.json
给定json包含一个对象数组:
{
"theList": [
{
"id": 1,
"name": "Horst"
},
{
"id": 2,
"name": "Fritz"
},
{
"id": 3,
"name": "Walter"
},
{
"id": 4,
"name": "Gerhart"
},
{
"id": 5,
"name": "Harmut"
}
]
}
我想过滤该列表只显示id为2和4的元素,因此预期输出为:
{
"id": 2,
"name": "Fritz"
},
{
"id": 4,
"name": "Gerhart"
}
如何使用jq过滤json? 我玩过选择和地图,但没有任何工作,例如:
$ jq '.theList[] | select(.id == 2) or select(.id == 4)' array.json
true
来自文档:
jq '.[] | select(.id == "second")'
输入
[{"id": "first", "val": 1}, {"id": "second", "val": 2}]
输出
{"id": "second", "val": 2}
我想你可以这样做:
jq '.theList[] | select(.id == 2 or .id == 4)' array.json
您可以在map
使用select
。
.theList | map(select(.id == (2, 4)))
或者更紧凑:
[ .theList[] | select(.id == (2, 4)) ]
虽然以这种方式编写的方式效率有点低,因为对于每个被比较的值,表达式都是重复的。 以这种方式编写它会更有效,也可能更具可读性:
[ .theList[] | select(any(2, 4; . == .id)) ]
在这里使用select(.id == (2, 4))
通常是低效的(见下文)。
如果你的jq有IN/1
,那么它可以用来实现更有效的解决方案:
.theList[] | select( .id | IN(2,3))
如果您的jq没有IN/1
,那么您可以按如下方式定义它:
def IN(s): first(select(s == .)) // false;
效率
查看效率低下的一种方法是使用debug
。 例如,以下表达式导致10次debug
调用,而实际上只需要检查9次相等:
.theList[] | select( (.id == (2,3)) | debug )
["DEBUG:",false]
["DEBUG:",false]
["DEBUG:",true]
{
"id": 2,
"name": "Fritz"
}
["DEBUG:",false]
["DEBUG:",false]
["DEBUG:",true]
{
"id": 3,
"name": "Walter"
}
["DEBUG:",false]
["DEBUG:",false]
["DEBUG:",false]
["DEBUG:",false]
索引/ 1
原则上,使用index/1
应该是有效的,但是在撰写本文时(2017年10月),它的实现虽然很快(用C语言编写),但效率很低。
这是一个使用索引的解决方案:
.theList | [ .[map(.id)|indices(2,4)[]] ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.