jq: error: Cannot index array with string

Viewed 4706

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?

4 Answers

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.

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'

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).

You need to pass numbers as JSON args. Here

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