目标是在维护原始json对象的同时,按百分比对账单费率数组进行排序。
[{
"id": 2,
"employee_observations": [{
"id": 1,
"bill_rates": [{
"bill_classification": "Lawn Mowing",
"percentage": 0.672399672399672
},
{
"bill_classification": "Trimming",
"percentage": 0.00163800163800164
},
{
"bill_classification": "Snow Removal",
"percentage": 0.630630630630631
},
{
"bill_classification": "Rock Removal",
"percentage": 0.00163800163800164
}
]
}]
}]
预期输出
[{
"id": 2,
"employee_observations": [{
"id": 1,
"bill_rates": [
{
"bill_classification": "Lawn Mowing",
"percentage": 0.672399672399672
},
{
"bill_classification": "Snow Removal",
"percentage": 0.630630630630631
},
{
"bill_classification": "Rock Removal",
"percentage": 0.00163800163800164
},
{
"bill_classification": "Trimming",
"percentage": 0.00163800163800164
}
]
}]
}]
如果我自己分解它,我可以得到预期的结果,但还没有找到正确的组合来保持上面嵌套版本中的格式不变。
[
{
"activity_classification": "Lawn Mowing",
"percentage": 0.672399672399672
},
{
"activity_classification": "Trimming",
"percentage": 0.00163800163800164
},
{
"activity_classification": "Snow Removal",
"percentage": 0.630630630630631
},
{
"activity_classification": "Rock Removal",
"percentage": 0.00163800163800164
}
]
jq"sort_by(.activity_percentage(| reverse"-结果
[
{
"activity_classification": "Lawn Mowing",
"percentage": 0.672399672399672
},
{
"activity_classification": "Snow Removal",
"percentage": 0.630630630630631
},
{
"activity_classification": "Rock Removal",
"percentage": 0.00163800163800164
},
{
"activity_classification": "Trimming",
"percentage": 0.00163800163800164
}
]
使用更新运算符|=
来保留整体结构,并使用负比较值-.percentage
按降序排序:
jq '.[].employee_observations[].bill_rates |= sort_by(-.percentage)'
[
{
"id": 2,
"employee_observations": [
{
"id": 1,
"bill_rates": [
{
"bill_classification": "Lawn Mowing",
"percentage": 0.672399672399672
},
{
"detection_classification": "Snow Removal",
"percentage": 0.630630630630631
},
{
"detection_classification": "Trimming",
"percentage": 0.00163800163800164
},
{
"detection_classification": "Rock Removal",
"percentage": 0.00163800163800164
}
]
}
]
}
]
演示