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

如何用PowerShell解析带表头和嵌套项的JSON并转为行数据

问题解决思路

原始JSON数据

{
    "TotalCount": 2,
    "Data": [
        {
            "ID": 9663696221792,
            "Code": "08099991",
            "Items": [
                {
                    "Amount": 5.05,
                    "LineNo": 1
                },
                {
                    "Amount": 16.08,
                    "LineNo": 2
                }               
            ]
        },
        {
            "ID": 9663696221793,
            "Code": "08028001",
            "Items": [
                {
                    "Amount": 26.13,
                    "LineNo": 1
                }
            ]
        }
    ]
}

问题说明

需要将上述JSON转换为包含表头行(Cost为对应Items的Amount总和)和每个嵌套项行的表格数据。现有PowerShell代码中,内层循环会遍历Data数组中所有Items,而非当前$root对应的Items,导致逻辑错误。

修正后的PowerShell代码

$array = Get-Content -Path 'response.json' | ConvertFrom-Json

# 初始化结果存储数组
$result = @()

foreach ($root in $array.Data) {
    # 计算当前条目下所有Items的Amount总和
    $totalCost = ($root.Items | Measure-Object -Property Amount -Sum).Sum
    
    # 添加表头行(用"表头"标识LineNo区分明细行)
    $result += [PSCustomObject]@{
        ID      = $root.ID
        Code    = $root.Code
        Cost    = $totalCost
        LineNo  = "表头"
        Amount  = ""
    }
    
    # 遍历当前$root对应的Items,生成明细行
    foreach ($item in $root.Items) {
        $result += [PSCustomObject]@{
            ID      = $root.ID
            Code    = $root.Code
            Cost    = ""
            LineNo  = $item.LineNo
            Amount  = $item.Amount
        }
    }
}

# 输出格式化后的表格
$result | Format-Table -AutoSize

关键修正点

  • 内层循环改为遍历$root.Items,仅处理当前$root对应的嵌套项,而非整个Data数组的所有Items
  • 使用Measure-Object计算每个条目下Amount的总和,作为表头行的Cost值
  • 通过自定义对象分别构建表头行和明细行,最终组合成符合要求的表格结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 22:46:08