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

使用PowerShell递归搜索JSON字符串并返回键路径与值

PowerShell递归搜索JSON中包含指定字符串的键值

核心思路

别把JSON转成哈希表,直接用ConvertFrom-Json生成的PSCustomObject遍历——它能完整保留JSON的嵌套结构(对象、数组)。通过递归函数跟踪每个键的完整路径,检查值是否包含目标字符串即可。

完整实现代码

function Search-JsonValue {
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        $InputObject,
        [Parameter(Mandatory)]
        [string]$SearchString,
        [string]$CurrentPath = ''
    )

    process {
        # 处理JSON对象(PSCustomObject类型)
        if ($InputObject -is [PSCustomObject]) {
            foreach ($prop in $InputObject.PSObject.Properties) {
                $newPath = if ($CurrentPath) { "$CurrentPath.$($prop.Name)" } else { $prop.Name }
                Search-JsonValue -InputObject $prop.Value -SearchString $SearchString -CurrentPath $newPath
            }
        }
        # 处理JSON数组
        elseif ($InputObject -is [array]) {
            for ($i = 0; $i -lt $InputObject.Count; $i++) {
                $newPath = "$CurrentPath[$i]"
                Search-JsonValue -InputObject $InputObject[$i] -SearchString $SearchString -CurrentPath $newPath
            }
        }
        # 处理普通值类型(字符串、数字等)
        else {
            $value = $InputObject.ToString()
            if ($value -match [regex]::Escape($SearchString)) {
                [PSCustomObject]@{
                    Path = $CurrentPath
                    Value = $InputObject
                }
            }
        }
    }
}

# 使用示例:搜索C:\myFile.json中值包含'corset'的键
$json = Get-Content -Path 'C:\myFile.json' -Raw | ConvertFrom-Json
Search-JsonValue -InputObject $json -SearchString 'corset'

关键细节说明

  1. 正确解析JSON:用Get-Content -Raw读取完整JSON文本,ConvertFrom-Json直接生成PSCustomObject,不会丢失嵌套结构信息。
  2. 递归遍历逻辑:
    • 遇到对象时,遍历每个属性并拼接路径(比如Header.Title),递归处理属性值;
    • 遇到数组时,遍历每个元素并在路径后添加索引(比如Data[2]),递归处理数组元素;
    • 遇到普通值时,转成字符串后检查是否包含目标字符串,匹配则输出完整路径和对应值。
  3. 特殊字符处理:用[regex]::Escape()转义搜索字符串中的特殊字符(比如.、*),避免正则匹配出错。

输出示例

假设JSON内容为{"Data":[{"Product":"red corset"},{"Price":199}]},运行后会输出:

Path      Value
----      -----
Data[0].Product red corset

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 23:10:52