【发布时间】:2021-12-10 04:13:21
【问题描述】:
如何打印带有排序对象数组的 JSON 输出? 我的 $result 对象必须保持原样,“好”或“坏”的顺序无关紧要, 我正在尝试按升序对按“count”属性排序的数组中的对象进行排序。
我的代码:
$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)
我的 JSON 输出是:
{
"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
}
]
}
如何打印这样的 JSON? (水果按“count”属性升序排序)
{
"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
}
]
}
[问题已修复]编辑解决方案:
$result.Good = $result.Good | Sort-Object count
$result.Bad = $result.Bad | Sort-Object count
Write-Output ($result | ConvertTo-Json)
【问题讨论】:
标签: arrays json powershell sorting pscustomobject