2

I have the following json:

[
  {
    "SG": [
      {
        "Id": "17",
        "GroupName": "fistGN",
        "Permissions": [
          {
            "Port": 80,
            "Protocol": "tcp"
          },
          {
            "Port": 8080,
            "Protocol": "tcp"
          },
          {
            "Port": 5080,
            "Protocol": "tcp"
          }
        ]
      },
      {
        "Id": "1",
        "GroupName": "secondGN",
        "Permissions": [
          {
            "Port": 80,
            "Protocol": "tcp"
          },
          {
            "Port": 8080,
            "Protocol": "tcp"
          },
          {
            "Port": 5080,
            "Protocol": "tcp"
          }
        ]
      }
    ]
  }
]

Is it possible to sort_by GroupName and then for each group by Permissions Port using a single command?

This is what I'm trying to do but that is not working as expected:

jq -s -S '.[].SG |= sort_by(.GroupName, .Permissions[].Port)' myfile.json
peak
  • 105,803
  • 17
  • 152
  • 177
douglaslps
  • 8,068
  • 2
  • 35
  • 54

1 Answers1

2

jq solution:

jq '.[0].SG |= (map(.Permissions |= sort_by(.Port)) | sort_by(.GroupName))' myfile.json
  • (map(.Permissions |= sort_by(.Port)) | sort_by(.GroupName)) - compound expression to separate 2 sort operations:
    • map(.Permissions |= sort_by(.Port)) - get a new array where each internal .Permissions array is sorted by key "Port" value
    • sort_by(.GroupName) - sort SG array items by "GroupName" key

The output:

[
  {
    "SG": [
      {
        "Id": "17",
        "GroupName": "fistGN",
        "Permissions": [
          {
            "Port": 80,
            "Protocol": "tcp"
          },
          {
            "Port": 5080,
            "Protocol": "tcp"
          },
          {
            "Port": 8080,
            "Protocol": "tcp"
          }
        ]
      },
      {
        "Id": "1",
        "GroupName": "secondGN",
        "Permissions": [
          {
            "Port": 80,
            "Protocol": "tcp"
          },
          {
            "Port": 5080,
            "Protocol": "tcp"
          },
          {
            "Port": 8080,
            "Protocol": "tcp"
          }
        ]
      }
    ]
  }
]
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105