I need to run a script where I have an array of ids, and a json that contains elements with these ids and more data. I need to filter/select the values that matches the ones in the array. For some reason, when running directly on bash I got good results with some of the things I've tried, but not when running with a script. Not sure if this may be relevant or I did something wrong when passing from one to the other
For example, if I have a json file like
[
{
"id": 1,
"value": 10
},
{
"id": 2,
"value": 100
},
{
"id": 3,
"value": 5
},
{
"id": 4,
"value": 17
},
{
"id": 5,
"value": 84
}
]
And the following array:
IDS=(1 2 3 4)
I need to retrieve the values 10, 100, 5 and 17.
I've tried some ways:
VALUES=$(jq --argjson IDS "$IDS" '.[] | select( $IDS =~ .id ) | .value' file.json)
VALUES=$(jq --argjson IDS "$IDS" '.[] | select( ${IDS[*]} =~ .id ) | .value' file.json)
# I have certainty that IDS will always have 4 elements, no more no less
VALUES=$(jq --argjson IDS "$IDS" '.[] | select( .id == ${IDS[0]} | .id == ${IDS[1]} | .id == ${IDS[2]} | .id == ${IDS[3]} ) | .value' file.json)
In all cases I'm getting `unexpected INVALID_CHARACTER (Unix shell quoting issues?)
Also, on the last case, when I replaced the ${IDS[n]} for a hardcoded number, it worked fine. Yet, I won't have the same numbers on each run, so I need that parametrized.
Any help would be great!
EDIT
Thanks everyone for the solutions. I kept the one I understood the most for now, but I'm really greatful with all