Json 如何使用jq按元素属性值过滤对象数组?
我喜欢使用以下方法过滤json文件: 给定包含对象数组的json:Json 如何使用jq按元素属性值过滤对象数组?,json,jq,Json,Jq,我喜欢使用以下方法过滤json文件: 给定包含对象数组的json: { "theList": [ { "id": 1, "name": "Horst" }, { "id": 2, "name": "Fritz" }, { "id": 3, "name": "Walter" }, { "id": 4, "name": "Gerhart"
{
"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?我已经玩过select和map,但没有任何一个可以使用,例如:
$ jq '.theList[] | select(.id == 2) or select(.id == 4)' array.json
true
来自文档: 输入
[{“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在/1中有,则可以使用它来实现更高效的解决方案:
.theList[] | select( .id | IN(2,3))
如果jq在/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编写),但效率很低。每个人请注意:问题是关于,而不是jQuery.@T.J.Crowder YMMD^^^,我在问题中澄清了这一点:Djq'。列表[]选择(.id==2)或选择(.id==4)'array.json
产生:true
o.OIt返回这两个子句的求值,试试这个:jq'。列表[]选择(.id==2或.id==4)
jq。列表[]选择(.id==2或.id==4)array.json做了这个把戏,你可以更新你的答案:)聪明地使用!
.theList[] | select( .id | IN(2,3))
def IN(s): first(select(s == .)) // false;
.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]