首页 > 解决方案 > 如何使用 jq 获取数组值

问题描述

文件.json

{
   "Groups":[
      
   ],
   "Instances":[
      {
         "AmiLaunchIndex":0,
         "ImageId":"ami-id",
         "InstanceId":"i-123548874",
         "InstanceType":"c5.4xlarge",
         "KeyName":"kay",
         "LaunchTime":"dateValue",
         "Monitoring":{
            "State":"disabled"
         },
         "Placement":{
            "AvailabilityZone":"zone value",
            "GroupName":"",
            "Tenancy":"default"
         },
         "PrivateDnsName":"ip address",
         "PrivateIpAddress":"10.245.247.21",
         "ProductCodes":[
            
         ], 
and more json...

数组中只有一项。我想从 json中获取InstanceIdPrivateIpAddress 。我正在使用以下命令来获取值:

file.json | jq -r .Instances[].InstanceId
file.json | jq -r .Instances[].PrivateIpAddress


但我没有得到任何回应。

我尝试了其他堆栈溢出问题中提到的各种方法,但仍然没有得到正确的响应。

我期待以下回应

i-123548874
10.245.247.21

标签: linuxjqaws-cli

解决方案


$ cat file.json | jq -r .Instances[].PrivateIpAddress
10.245.247.21

$ cat file.json | jq -r .Instances[].InstanceId
i-123548874

或者

$ jq -r .Instances[].PrivateIpAddress file.json
10.245.247.21

$ jq -r .Instances[].InstanceId file.json
i-123548874

推荐阅读