简体   繁体   English

在bash脚本中循环JSON数组并通过JQ提取数据

[英]Loop on JSON array in bash script and pull data through JQ

i want to pull data from jSON file through jq in bash script.我想通过 bash 脚本中的 jq 从 json 文件中提取数据。 I have 50 plus SG objects in JSON .我在 JSON 中有 50 多个 SG 对象。

here is an example of one SG .这是一个 SG 的示例。 I want to print a VPC id and group id in one line and so on for another objects.我想在一行中打印 VPC id 和组 id,以此类推为另一个对象。

Solution i tried :我试过的解决方案:

jq -c . $old |
while IFS= read -r obj; do 
    vpcidold=$( printf '%s' "$obj" | jq '.SecurityGroups[].VpcId')
    securityidold=$( printf '%s' "$obj" | jq '.SecurityGroups[].GroupId')
    echo "${vpcidold}||${securityidold}"
done > oldtest.json

it is working file but giving data in a line by line and want to do more optimised this with for loop.它是工作文件,但逐行提供数据,并希望使用 for 循环对其进行更多优化。

How can I create a loop on JSON array to get desire output如何在 JSON 数组上创建循环以获得所需的输出

    "SG": [
      {
        "Description": "des",
        "GroupName": "Gpname",
        "IpPermissions": [
          {
            "FromPort": 80,
            "IpProtocol": "tcp",
            "IpRanges": [
              {
                "CidrIp": "0.0.0.0/0"
              }
            ],
            "Ipv6Ranges": [],
            "PrefixListIds": [],
            "ToPort": 80,
            "UserIdGroupPairs": []
          }
        ],
        "OwnerId": "123",
        "GroupId": "sg",
        "IpPermissionsEgress": [
          {
            "IpProtocol": "-1",
            "IpRanges": [
              {
                "CidrIp": "0.0.0.0/0"
              }
            ],
            "Ipv6Ranges": [],
            "PrefixListIds": [],
            "UserIdGroupPairs": []
          }
        ],
        "Tags": [
          {
            "Key": "projectcode",
            "Value": "none"
          },
          {
            "Key": "sgid",
            "Value": "sg-123"
          }
        ],
        "VpcId": "vpc-123"
      }
    ]
  }, 

If the JSON file is just an array of the objects, you don't need to loop over them in bash.如果 JSON 文件只是一个对象数组,则不需要在 bash 中遍历它们。 jq will loop over them implicitely: jq将隐式循环它们:

jq -r '.[][][] | (.VpcId + "||" + .GroupId)' file.json

Tested on the following input:在以下输入上测试:

[
    { "SG": [
        {
            "Description": "des",
            "GroupName": "Gpname",
            "GroupId": "sg",
            "VpcId": "vpc-123"
        }
    ] },
    { "SG": [
        {
            "Description": "des",
            "GroupName": "xyz",
            "GroupId": "sg-12345",
            "VpcId": "vpc-12345"
        }
    ] }
]

Output:输出:

vpc-123||sg
vpc-12345||sg-12345

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM