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

如何在PowerShell中编写递归函数处理任意JSON数据

PowerShell递归处理任意JSON节点的函数实现

问题背景

给定任意结构的JSON(示例如下),需要编写PowerShell函数,递归遍历每个节点:

{
  "inventory": {
    "trucks": {
      "wheels": {
        "count": 4,
        "brand": "fireyear"
      },
      "engine": {
        "valveCount": 3
      }
    },
    "planets": {
      "ringed": [
        "saturn"
      ],
      "questionable status": [
        "pluto"
      ]
    }
  }
}

函数需接收节点路径(根节点传空字符串)和当前节点作为参数,判断节点是否为PSCustomObject(JSON转PowerShell后的对象类型):

  • 若不是对象/数组类型,直接处理该节点的值
  • 若是对象/数组类型,递归处理每个子节点

函数实现

function Process-JsonNode {
    param(
        [string]$CurrentPath,
        [psobject]$Node
    )

    # 处理JSON对象类型(PSCustomObject)
    if ($Node -is [PSCustomObject]) {
        # 遍历所有未知键的属性
        foreach ($prop in $Node.PSObject.Properties) {
            # 拼接子节点路径
            $newPath = if ([string]::IsNullOrEmpty($CurrentPath)) {
                $prop.Name
            } else {
                "$CurrentPath.$($prop.Name)"
            }
            # 递归处理子节点
            Process-JsonNode -CurrentPath $newPath -Node $prop.Value
        }
    }
    # 处理数组类型
    elseif ($Node -is [array]) {
        for ($i = 0; $i -lt $Node.Count; $i++) {
            $newPath = "$CurrentPath[$i]"
            Process-JsonNode -CurrentPath $newPath -Node $Node[$i]
        }
    }
    # 处理非对象/数组的基础类型值
    else {
        # 此处替换为你实际的业务处理逻辑,示例为输出路径和值
        Write-Host "路径: $CurrentPath | 值: $Node"
    }
}

使用示例

# 读取JSON文件并转换为PowerShell对象
$jsonData = Get-Content -Path "big-blob-of-json.json" | ConvertFrom-Json
# 从根节点开始递归处理
Process-JsonNode -CurrentPath "" -Node $jsonData

关键说明

  • 利用$Node.PSObject.Properties遍历任意属性,无需提前知晓键名
  • 兼容数组类型的递归处理,通过索引构建数组元素的路径
  • 根节点传空字符串时,自动将第一个属性名作为路径起始

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 11:13:24