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?
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>
;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With