Home > other >  Use intermediate jq value to filter input array
Use intermediate jq value to filter input array

Time:08-18

I have an array of strings and I want to retrieve the one before the one matching a certain value.

I'm currently doing this using multiple commands but I can't figure out a shorter way to do it in jq.

This is the relevant part, we have some JSON data and we want to find the element before the one specificed in $VERSION (which is used provided)

someJson='{ "versions":["0.1.0","0.2.0","0.3.0","0.3.1", "0.5.0-rc.1","0.5.0"] }'
allVersions=$(echo $someJson | jq '.versions')
INDEX=$(echo $allVersions | jq --arg version $VERSION '. | to_entries | .[] | select(.value==$version) | .key - 1')
echo $allVersions | jq -r --arg index $INDEX '.[($index | tonumber)]'

Is there a way to do this without the intermediate variables? I can't find a way to access the previous data in jq alone.

I'm looking to do something like:

CodePudding user response:

Use the index function to get the position:

jq --arg v "0.3.0" -r '.versions | .[index($v) - 1]' input.json
0.2.0

Demo

  • Related