Consider the following json:
[
{
"val": 1,
"name": "a"
},
{
"val": 2,
"name": "b"
},
{
"val": 3,
"name": "c"
}
]
I want to pass an argument of space separated elements to jq and filter only these elements that have names matching to one of the argument elements. The following does not work, and I do not understand why – it only filters the first element. I suspect that $input
is not updated. I do not know how to "join streams" to make it possible to use both streams at the same time – I have one stream the input and another is $names | split(" ")
.
$ jq -r --arg names 'a c' '.[] | select(. as $input | $names | split(" ") | index($input.name) == 0)' 1.json
{
"val": 1,
"name": "a"
}
I have jq-1.5 available.
2
Answers
You can make the comparison using
IN
(orany
for jq < 1.6), for example:If your search keys are unique, you could also build up an
INDEX
, and lookup the fields:Output:
Easiest is probably to split your
names
into an array first, then useIN
to filter your stream:Or using
any
:(the latter simply inlines
IN
:def IN(s): any(s == .; .);
)