unai abrisketa sanchez
unai abrisketa sanchez

Reputation: 386

jq: error: Cannot index array with string

I`m trying to do a bash script for a checkpoint management server api and I am experiencing some problems. I want to get the value in a json dictionary and for that I have to use variables. I am entering this command:

echo $rulebase | jq --arg n "$0" '.rulebase[$n].to'

and I get the next error:

jq: error: Cannot index array with string

However, If i use :

echo $rulebase | jq  '.rulebase[0].to'

I get the result that I need. I dont know how to use the variables when they are a number, can anyone help me?

Upvotes: 5

Views: 6717

Answers (4)

oliv
oliv

Reputation: 13239

You need to convert the string that you give to your script to a number.

echo "$rulebase" | jq --arg n "$1" '.rulebase[$n|tonumber].to'

Upvotes: 8

peak
peak

Reputation: 116670

If you want to pass in a numeric value, use

—-argjson

instead of —-arg, which is for JSON string values.

If your jq does not support —argjson, then now would be an excellent time to upgrade if possible; otherwise, you could use tonumber.

Upvotes: 5

oguz ismail
oguz ismail

Reputation: 50750

You need to pass numbers as JSON args. Here

echo "$rulebase" | jq --argjson n "$my_variable" '.rulebase[$n].to'

Upvotes: 1

Armali
Armali

Reputation: 19375

If you have the index number in $0, just let the shell insert it by using appropriate quotes:

echo $rulebase | jq ".rulebase[$0].to"

(this being strange, having a number in $0, which normally is the program name).

Upvotes: 1

Related Questions