没有无限过滤链的JQ对象选择

时间:2018-05-02 16:21:18

标签: json select 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":[]
}
  • 要提取列表bx为“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,那么这很好,但如果我想做一个OR怎么办?例如,获取jq为“bar”x OR以“X”结尾的对象的s程序是什么? jq是否有|OR|过滤器?

jq '.["b"][] | select(.x == "bar") |OR| select(.s | endswith("X"))' < file.json

或者我只是做错了?我是否试图重新发明一些标准jq算法来选择对象?

1 个答案:

答案 0 :(得分:2)

直截了当(在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}