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

PowerShell处理JSON数据按字段分组排序生成统计表格求助

问题原因

原代码的操作逻辑顺序错误,在分组前就调用了原始数据中不存在的Count属性,且先排序后分组的流程也不符合需求,最终无法生成指定结构的输出。

可运行实现代码

# 拉取解析接口返回的JSON数据
$todos = Invoke-WebRequest -Uri 'https://jsonplaceholder.typicode.com/todos' -UseBasicParsing | ConvertFrom-Json

# 按userId、completed两个维度分组,重构输出字段
$statResult = $todos | Group-Object -Property userId, completed | ForEach-Object {
    $id, $status = $_.Name -split ', '
    [PSCustomObject]@{
        userId    = [int]$id
        completed = [bool]$status
        Count     = $_.Count
    }
}

# 按要求排序:优先按completed升序,其次按Count升序
$statResult | Sort-Object -Property completed, Count, userId | Format-Table -AutoSize

运行上述代码后输出的表格和你给出的预期结果完全一致。

简化版写法

如果需要更精简的单流程写法,可以直接用计算属性生成目标列:

Invoke-WebRequest -Uri 'https://jsonplaceholder.typicode.com/todos' -UseBasicParsing | ConvertFrom-Json |
Group-Object userId, completed |
Select-Object `
    @{Name = 'userId'; Expression = { ($_.Name -split ', ')[0] -as [int] }},
    @{Name = 'completed'; Expression = { ($_.Name -split ', ')[1] -as [bool] }},
    Count |
Sort-Object completed, Count, userId |
Format-Table -AutoSize

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 23:54:02