Reputation: 997
When I do this:
$ jq -cr '.arr[]|select(.id==-1)|.desc' <<<$'{"arr":[{"id":-1,"desc":"foo"},{"id":100}]}'
foo
works as expected.
But if I try to pass a variable in place of the index:
$ lookup=-1; jq -cr --arg l "$lookup" '.arr[]|select(.id==$l)|.desc' <<<$'{"arr":[{"id":-1,"desc":"foo"},{"id":100}]}'
no output
Doesn't produce output this time.
How to fix this so that it works with shell variable lookup
?
Upvotes: 0
Views: 310
Reputation: 36231
Use --argjson
instead of --arg
.
--arg l "$lookup"
makes $l
a string. With --argjson l "$lookup"
it is interpreted as JSON, a number in this case, just as was 1
in .id==-1
, your working example.
Or do an additional operation to use the tonumber
flag to $l
, indicating that you want the operation on a numeric equivalent of the string value passed. i.e. ($l|tonumber)
Upvotes: 1