Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make jq treat argument as numeric instead of string?

Tags:

bash

jq

How to make jq treat an input argument as numeric instead of string? In the following example, CURR_INDEX is a Bash variable which has array index value that I want to extract.

jq --arg ARG1 $CURR_INDEX '.[$ARG1].patchSets' inputfile.json

I get the following error:

jq: error: Cannot index array with string

I tried the workaround of using bash eval but some jq filters do not work properly in eval statements.

like image 279
harish Avatar asked Feb 12 '16 10:02

harish


2 Answers

You can convert it to a number, like this:

jq --arg ARG1 1 '.[$ARG1|tonumber]' <<< '["foo". "bar"]'
"bar"
like image 92
hek2mgl Avatar answered Feb 24 '23 23:02

hek2mgl


--arg always binds the value as a string. You can use --argjson (introduced in version 1.5) to treat the argument as a json-encoded value instead.

jq --argjson ARG1 $CURR_INDEX '.[$ARG1].patchSets' inputfile.json

To see it in action, you can reproduce your original error:

$ jq --argjson ARG1 '"1"' '.[$ARG1]' <<< '["foo", "bar"]'
jq: error (at <stdin>:1): Cannot index array with string "1"

then correct it:

$ jq --argjson ARG1 1 '.[$ARG1]' <<< '["foo", "bar"]'
"bar"
like image 45
chepner Avatar answered Feb 24 '23 23:02

chepner