如何将整数作为参数放在jq中?

时间:2021-03-27 11:17:20

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.

我一直在尝试使用jq来解析从aws cli返回的json文件,但我仍然坚持使用索引号引用数组的问题。我需要这样做,因为我想导出一个描述特定格式的安全组的文本文件,包括所有入站和出站规则。

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?

有没有办法解决?

1 个解决方案

#1


4  

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.

您可能必须使用命令行arg --argjson或fromjson filter将参数转换为数字。数组只能由int索引,并且使用--arg将输入保持为字符串。

$ jq --argjson i "$i" '.SecurityGroups[$i]'
$ jq --arg i "$i" '.SecurityGroups[$i|fromjson]'

#1


4  

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.

您可能必须使用命令行arg --argjson或fromjson filter将参数转换为数字。数组只能由int索引,并且使用--arg将输入保持为字符串。

$ jq --argjson i "$i" '.SecurityGroups[$i]'
$ jq --arg i "$i" '.SecurityGroups[$i|fromjson]'