简体   繁体   中英

Use intermediate jq value to filter input array

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM