harish
harish

Reputation: 1924

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

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.

Upvotes: 10

Views: 3780

Answers (2)

chepner
chepner

Reputation: 531035

--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"

Upvotes: 4

hek2mgl
hek2mgl

Reputation: 157947

You can convert it to a number, like this:

jq --arg ARG1 1 '.[$ARG1|tonumber]' <<< '["foo". "bar"]'
"bar"

Upvotes: 5

Related Questions