Home > Blockchain >  How to get the index of element using jq
How to get the index of element using jq

Time:08-17

I want to get the index of a element from the array.

Link: https://api.github.com/repos/checkstyle/checkstyle/releases

I want to fetch the tag_name.

I generally use this command to get my latest release tag:

LATEST_RELEASE_TAG=$(curl -s https://api.github.com/repos/checkstyle/checkstyle/releases/latest \
                       | jq ".tag_name")

But now I want previous releases too so I want the index of a particular tag name. For eg: tag_name = "10.3.1"

Also, I am thinking to use mathematical reduction to get the other previous release if I get a particular index number like: ( 'index of 10.3.1' - 1) Any thought regarding this?

CodePudding user response:

Just index of "checkstyle-10.3.1":

curl -s https://api.github.com/repos/checkstyle/checkstyle/releases | jq '[.[].tag_name] | to_entries | .[] | select(.value=="checkstyle-10.3.1") | .key'

Release before "checkstyle-10.3.1":

curl -s https://api.github.com/repos/checkstyle/checkstyle/releases | jq '([.[].tag_name] | to_entries | .[] | select(.value=="checkstyle-10.3.1") | .key) as $index | .[$index 1]'

Release "checkstyle-10.3.1"

curl -s https://api.github.com/repos/checkstyle/checkstyle/releases | jq '.[] | select(.tag_name=="checkstyle-10.3.1")'

CodePudding user response:

Here's a general-purpose function to get the index of something in an array:

  # Return the 0-based index of the first item in the array input
  # for which f is truthy, else null
  def index_by(f):
    first(foreach .[] as $x (-1;
      . 1;
      if ($x|f) then . else empty end)) // null;

This can be used to retrieve the item immediately before a target as follows:

jq '
  def index_by(f): first(foreach .[] as $x (-1; . 1; if ($x|f) then . else empty end)) // null;

  index_by(.tag_name == "checkstyle-10.3.1") as $i
  | if $i then .[$i - 1] else empty end
'
  • Related