【问题标题】:sort json array by value jq bash按值排序json数组jq bash
【发布时间】:2020-02-18 11:38:15
【问题描述】:

我想根据groupId 在数组下方排序,这样groupId 较小的键在数组中排在第一位。

[
  {
    "groupId": 11,
    "lowerThreshold": 33,
    "target": {
      "alarm_id": 22
    },
    "thresholdPeriod": 3,
    "upperThreshold": 44
  },
  {
    "groupId": 31,
    "lowerThreshold": 33,
    "target": {
      "alarm_id": 122
    },
    "thresholdPeriod": 3,
    "upperThreshold": 44
  },
  {
    "groupId": "0",
    "target": {
      "alarm_id": "69"
    },
    "upperThreshold": "20",
    "lowerThreshold": "10",
    "thresholdPeriod": "5"
  }
]

期待

[
  {
    "groupId": "0",
    "target": {
      "alarm_id": "69"
    },
    "upperThreshold": "20",
    "lowerThreshold": "10",
    "thresholdPeriod": "5"
  },
  {
    "groupId": 11,
    "lowerThreshold": 33,
    "target": {
      "alarm_id": 22
    },
    "thresholdPeriod": 3,
    "upperThreshold": 44
  },
  {
    "groupId": 31,
    "lowerThreshold": 33,
    "target": {
      "alarm_id": 122
    },
    "thresholdPeriod": 3,
    "upperThreshold": 44
  }
]

【问题讨论】:

  • 你的groupIds 是非统一类型,例如:"0"string 类型,而其他是 numerical 类型。如果您允许将 groupId 值标准化为相同类型,则会容易得多,那么排序将是微不足道的。否则(如果您的要求是保持它们的原始格式),答案会有点复杂
  • 在后一种情况下,答案是jq 'sort_by(.groupId | tonumber)'
  • 谢谢@Dmitry。我得到了所需的答案。
  • jq 的排序是异构的,因此使用tonumber 可能是不必要的(甚至是错误的,取决于 .groupId 值的实际范围)。不过,正如@Dmitry 所说,明确要求会有所帮助(希望对每个人都有帮助)。

标签: json bash jq


【解决方案1】:

您可以使用sort_by,如下所示:

jq 'sort_by(.groupId)'

【讨论】:

  • 如果 groupId 是数字,这个答案是正确的。其他明智的 *jq 'sort_by(.groupId | tonumber)' *可以使用。
  • @arun_kushwaha - sortsort_by 都不需要同质化。
猜你喜欢
  • 2012-01-03
  • 2020-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-17
  • 1970-01-01
  • 1970-01-01
  • 2014-04-21
相关资源
最近更新 更多