How can I print a JSON output with sorted array of objects? My $result object must remain as it is, the order of "Good" or "Bad" doesn't matter, I'm trying to sort the objects in the arrays sorted by "count" property in ascending order.
My code:
$result = [PSCustomObject]@{
Good = @()
Bad = @()
}
$food = [PSCustomObject]@{
name = "Banana"
count = 2
}
if ($food.count -gt 3) { $result.Good += $food }
else { $result.Bad += $food }
$sortGood = $result.Good | Sort-Object count
$sortBad = $result.Bad | Sort-Object count
Write-Output ($result | ConvertTo-Json)
My JSON output is:
{
"Good": [
{
"name": "Apple"
"count": 10
},
{
"name": "Lime"
"count": 5
},
{
"name": "Peach"
"count": 7
}
],
"Bad": [
{
"name": "Banana"
"count": 2
},
{
"name": "Kiwi"
"count": 1
},
{
"name": "Orange"
"count": 3
}
]
}
How can I print a JSON that looks like this? (fruits sorted by "count" property in ascending order)
{
"Good": [
{
"name": "Lime"
"count": 5
},
{
"name": "Peach"
"count": 7
},
{
"name": "Apple"
"count": 10
},
],
"Bad": [
{
"name": "Kiwi"
"count": 1
},
{
"name": "Banana"
"count": 2
},
{
"name": "Orange"
"count": 3
}
]
}
[Problem fixed] Edited solution:
$result.Good = $result.Good | Sort-Object count
$result.Bad = $result.Bad | Sort-Object count
Write-Output ($result | ConvertTo-Json)