Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I put integer as an argument in jq?

Tags:

json

jq

jsawk

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?

like image 547
zoonoo Avatar asked Aug 03 '16 19:08

zoonoo


People also ask

How do you pass arguments to jq?

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.

What is jq expression?

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.

What is jq command in ubuntu?

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.


1 Answers

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]'
like image 99
Jeff Mercado Avatar answered Oct 10 '22 17:10

Jeff Mercado