Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I pass argument as index to jq?

Tags:

json

parsing

jq

Hi I would like to access a given element in the json array as below:

$ echo '[  { "CT" : "OS1"  , "VERSION" : "3" } , { "CT" : "OS2"  , "VERSION" : "3" } ]'  | jq '.[1]'
{
  "CT": "OS2",
  "VERSION": "3"
}

However I would like to use a variable (from the environment in the future) replacing the index '1' in the command above but this produces an error.

echo '[  { "CT" : "OS1"  , "VERSION" : "3" } , { "CT" : "OS2"  , "VERSION" : "3" } ]'  | jq --arg index 1 '.[$index]'
jq: error (at <stdin>:1): Cannot index array with string "1"

It looks like it cannot parse this 1 as a numerical value once resolved like this. Is somebody able to help me?

like image 934
Chubs Avatar asked Jan 01 '23 18:01

Chubs


2 Answers

You can use --argjson option:

jq --argjson index 1 '.[$index]'

As mentioned in the jq --help:

--argjson a v set variable $a to JSON value <v>;

like image 82
oliv Avatar answered Jan 11 '23 10:01

oliv


If you have jq 1.4 or older, you could use the tonumber function:

jq --arg index 1 '.[$index | tonumber]'

For more recent versions, refer to oliv's answer.

like image 43
Benjamin W. Avatar answered Jan 11 '23 08:01

Benjamin W.