How can I put integer as an argument in jq?

人盡茶涼 提交于 2021-02-16 16:14:30

问题


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?


回答1:


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]'


来源:https://stackoverflow.com/questions/38752499/how-can-i-put-integer-as-an-argument-in-jq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!