You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell如何输出数组对象按count属性升序排序的JSON内容

PowerShell JSON输出数组内对象排序问题

在使用PowerShell开发时遇到JSON输出排序需求:需要保留$result对象的原有结构,Good、Bad两个键的顺序无需调整,仅要将两个键对应数组内的对象按count属性升序排序后再输出JSON。

原有实现代码

$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)

异常输出(数组未按count升序排序)

{
    "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
                }
            ] 
}

期望输出结果

{
    "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
                }
            ] 
}

修复方案

原有代码的问题在于:仅将排序后的结果赋值给了独立变量$sortGood、$sortBad,没有覆盖原对象$result内的对应属性,导致输出时仍使用未排序的原始数组。
替换原有排序逻辑为如下代码即可:

$result.Good = $result.Good | Sort-Object count
$result.Bad  = $result.Bad | Sort-Object count
Write-Output ($result | ConvertTo-Json)

内容的提问来源于stack exchange,提问作者Adela

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 14:36:05