I have been trying to use jq to parse a json file returned from the aws cli, but I'm stuck with the problem of referencing an array using the index number. I need to do this because I want to export a text file describing the security groups in a specific format, including all the inbound and outbound rules.
for (( i=1; i<=groupCount; i++ )) ;
do
echo $i
echo $(echo "$input" | jq --arg i $i '.SecurityGroups[$i]')
done
This returns an error:
1
jq: error (at <stdin>:189): Cannot index array with string "1"
2
jq: error (at <stdin>:189): Cannot index array with string "2"
3
jq: error (at <stdin>:189): Cannot index array with string "3"
Is there any way around this?
Passing arguments to JQ is done with --arg <name> <value> as shown below. Inside the filter, you can access a --arg with $<name> . In this case $foo returns bar . Note also in this example the -n flag which is used to tell JQ to not expect any JSON input.
A jq program is a "filter": it takes an input, and produces an output. There are a lot of builtin filters for extracting a particular field of an object, or converting a number to a string, or various other standard tasks.
The JQ command is used to transform JSON data into a more readable format and print it to the standard output on Linux. The JQ command is built around filters which are used to find and print only the required data from a JSON file.
You would either have to use the command line arg --argjson
or fromjson
filter to convert the argument to a number. Arrays are may only be indexed by ints and using --arg
keeps the input as a string.
$ jq --argjson i "$i" '.SecurityGroups[$i]'
$ jq --arg i "$i" '.SecurityGroups[$i|fromjson]'
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