dg99
dg99

Reputation: 5663

JQ object selection without endless filter chains

I'm having difficulty using jq (1.5) to parse deeply nested JSON structures, and I feel like I'm using it wrong. Take this example JSON input:

{
 "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":[]
}

If I want to apply a regular expression test, though, or any other test that requires a string input (bearing in mind that I still need object outputs), I think I have no choice but to chain filters. For example ...

Which is fine if I'm always doing boolean ANDs, but what if I want to do an OR? For example, what is the jq program to get objects where x is "bar" OR s ends in "X"? Does jq have an |OR| filter?

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

Or am I just doing it wrong? Am I attempting to reinvent some standard jq algorithm for selecting objects?

Upvotes: 1

Views: 127

Answers (1)

RomanPerekhrest
RomanPerekhrest

Reputation: 92874

Straightforwardly (specify all of your conditions within select function):

jq -c '.b[] | select(.x == "bar" or (.s | endswith("X")))' file.json

The output:

{"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}

Upvotes: 2

Related Questions