是否可以使用jq进行sort_by再次按子项进行sort_by

时间:2018-03-02 11:27:28

标签: json sorting jq

我有以下json:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
    <div ng-controller="myCtrl">
        <select id="connectTV" aria-label="How many Dish TVs" ng-model="connectTVs" ng-change="onChangeMethod()" class="selector" aria-required="true" ng-options="noOfTV as noOfTV.value for noOfTV in noOfTVs">
</select>
    </div>
</div>

是否可以使用单个命令通过权限端口对Group_进行排序,然后对每个组进行排序?

这是我尝试做的事情,但这并没有按预期运作:

[
  {
    "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"
          }
        ]
      }
    ]
  }
]

1 个答案:

答案 0 :(得分:2)

jq 解决方案:

jq '.[0].SG |= (map(.Permissions |= sort_by(.Port)) | sort_by(.GroupName))' myfile.json
  • (map(.Permissions |= sort_by(.Port)) | sort_by(.GroupName)) - 复合表达式,用于分隔2个排序操作:
    • map(.Permissions |= sort_by(.Port)) - 获取一个新数组,其中每个内部.Permissions数组按键"Port"值排序
    • sort_by(.GroupName) - 按SG
    • 排序"GroupName"个数组项

输出:

[
  {
    "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"
          }
        ]
      }
    ]
  }
]