没有无限过滤链的JQ对象选择
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了没有无限过滤链的JQ对象选择相关的知识,希望对你有一定的参考价值。
我在使用jq (1.5)
来解析深层嵌套的JSON结构时遇到了困难,我觉得我使用它错了。以JSON输入为例:
{
"a":[],
"b":[
{"x":"bar", "s":"FX", "f":["blorg","blarg","blurb"], "v":true},
{"x":"bar", "s":"EX", "f":["blorg","blarg","bloob"], "v":false},
{"x":"bar", "s":"XT", "f":["blorg","blart","bloop"], "v":true},
{"x":"bar", "s":"IJ", "f":["blorg","bleep","glarp"], "v":true},
{"x":"foo", "s":"IX", "f":["porg","parg","pork","peep"], "v":true},
{"x":"baz", "s":"AB", "f":["zing","zang","zoop"], "v":false}
],
"c":[]
}
- 要在列表
b
中提取x
为“bar”的对象很简单:jq '.["b"][] | select(.x == "bar")' < file.json
- 要进一步限制具有特定值
s
的对象也很简单:jq '.["b"][] | select(.x == "bar" and .s == "FX")' < file.json
但是,如果我想应用正则表达式测试,或者需要字符串输入的任何其他测试(请记住我仍然需要对象输出),我想我别无选择,只能链接过滤器。例如 ...
- 要限制
s
以“X”结尾的对象,遗憾的是以下内容不是jq
中的内容:jq '.["b"][] | select(.x == "bar" and .s.endswith("X"))' < file.json
相反,我认为我必须这样做:jq '.["b"][] | select(.x == "bar") | select(.s | endswith("X"))' < file.json
- 与
s
类似,包含“X”:jq '.["b"][] | select(.x == "bar") | select(.s | test("X"))' < file.json
如果我总是做布尔AND
s,这很好,但如果我想做一个OR
怎么办?例如,什么是jq
程序获取x
为“bar”的对象OR
s
以“X”结尾? jq
有|OR|
过滤器吗?
jq '.["b"][] | select(.x == "bar") |OR| select(.s | endswith("X"))' < file.json
或者我只是做错了?我是否试图重新发明一些标准的jq
算法来选择对象?
答案
直截了当(在select
函数中指定所有条件):
jq -c '.b[] | select(.x == "bar" or (.s | endswith("X")))' file.json
输出:
{"x":"bar","s":"FX","f":["blorg","blarg","blurb"],"v":true}
{"x":"bar","s":"EX","f":["blorg","blarg","bloob"],"v":false}
{"x":"bar","s":"XT","f":["blorg","blart","bloop"],"v":true}
{"x":"bar","s":"IJ","f":["blorg","bleep","glarp"],"v":true}
{"x":"foo","s":"IX","f":["porg","parg","pork","peep"],"v":true}
以上是关于没有无限过滤链的JQ对象选择的主要内容,如果未能解决你的问题,请参考以下文章