【发布时间】: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 所说,明确要求会有所帮助(希望对每个人都有帮助)。