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

PowerShell解析JSON无法遍历dependencies节点获取键值对的解决方法

问题原因

你遇到遍历失败的核心原因是:ConvertFrom-Json 反序列化JSON后,$json.dependencies 是 PSCustomObject 类型,它本身不是可枚举的键值对集合,直接用foreach遍历只会把整个dependencies对象当成单个循环项,所以你看到循环只执行1次,所有取包名、版本的操作都作用在整个dependencies对象上,自然返回空或者错误值。
另外你读取文件时没加-Raw参数,低版本PowerShell中Get-Content会按行返回字符串数组,可能导致JSON解析异常。

具体实现方法

1. 正确遍历dependencies对象

通过PSCustomObject自带的PSObject.Properties成员,就能拿到该对象下所有属性组成的可遍历集合,每个集合项对应一个依赖的键值对。

2. 获取单个依赖的包名和版本号

遍历PSObject.Properties得到的每个属性项,直接通过.Name属性取包名(键),.Value属性取版本号(值)即可。

修正后的完整可运行脚本
$targetName = "otherPackagenName"
Write-Host "Trying to get version # of $targetName if it exists inside project.json"

# 加-Raw参数一次性读取完整文件内容,避免JSON解析异常
$json = Get-Content .\project.json -Raw | ConvertFrom-Json
$dependencies = $json.dependencies

# 遍历属性集合,拿到每个单独的依赖项
foreach ($dep in $dependencies.PSObject.Properties) {
    $depName = $dep.Name
    $depVersion = $dep.Value
    Write-Host "Scanned dependency: Name = $depName, Version = $depVersion"

    if ($depName -eq $targetName) {
        Write-Host "Found target package! Corresponding version is $depVersion"
        break # 找到目标后直接跳出循环,不需要继续遍历
    }
}
快捷查询方式(无需遍历全量依赖)

如果你的需求只是查询指定包的版本,不需要遍历所有依赖,可以直接判断目标包名是否是dependencies的属性,直接取值即可,代码更简洁:

$targetName = "otherPackagenName"
$json = Get-Content .\project.json -Raw | ConvertFrom-Json
$depList = $json.dependencies.PSObject.Properties.Name

if ($depList -contains $targetName) {
    $targetVersion = $json.dependencies.$targetName
    Write-Host "Package $targetName exists, version is $targetVersion"
} else {
    Write-Host "Target package is not declared in dependencies"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 21:36:21