The goal is to sort the bill rates array by the percentage while maintaining the original json object.
[{
"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
}
]
}]
}]
Output expected
[{
"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
}
]
}]
}]
If I break it out by itself I can get to the expected result but haven't found the right combo to keep the format intact in the nested version above.
[
{
"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' - Results
[
{
"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
}
]
CodePudding user response:
Use the update operator |=
to preserve the overall structure, and a negative comparison value -.percentage
to sort in descending order:
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
}
]
}
]
}
]