PowerShell将JSON转为哈希表时抛出‘Cannot index into a null array’错误
问题分析与解决方案
错误原因
报错Cannot index into a null array的核心问题是你没提前初始化$hashtable变量。PowerShell里如果直接对未定义的变量做索引赋值操作,就会触发这个错误。
另一台机器能正常运行,是因为那台机器的PowerShell会话之前已经创建过$hashtable变量,当前脚本复用了这个已存在的变量;而报错的机器会话里没有这个变量,自然执行失败。
修复后的脚本
在脚本开头添加哈希表初始化语句就能解决:
# 先初始化一个空哈希表 $hashtable = @{} $json_path = Get-ChildItem "test.json" -Recurse | ForEach-Object { $_.FullName } $json = Get-Content $json_path -Raw | ConvertFrom-Json $json.psobject.properties | ForEach-Object { $hashtable[$_.Name] = $_.Value } # 可选:打印哈希表验证结果 $hashtable
额外优化建议
- 如果目录里只有一个
test.json,用-Recurse可能会找到多个同名文件,建议加上-File明确找文件,或者限制只取第一个结果:$json_path = Get-ChildItem -Path . -Name "test.json" -File -Recurse | Select-Object -First 1 -ExpandProperty FullName - 原脚本只能把顶层JSON属性转成哈希表,嵌套的对象(比如
app数组里的子对象)还是PSCustomObject。如果需要把所有嵌套结构都转成哈希表,可以用递归函数处理:function ConvertTo-Hashtable { param([Parameter(ValueFromPipeline)] $InputObject) process { if ($null -eq $InputObject) { return $null } if ($InputObject -is [System.Collections.IEnumerable] -and $InputObject -isnot [string]) { $collection = @() foreach ($item in $InputObject) { $collection += ConvertTo-Hashtable $item } return $collection } elseif ($InputObject -is [psobject]) { $hash = @{} foreach ($property in $InputObject.PSObject.Properties) { $hash[$property.Name] = ConvertTo-Hashtable $property.Value } return $hash } else { return $InputObject } } } # 用递归函数一键转换整个JSON结构 $hashtable = $json | ConvertTo-Hashtable
内容的提问来源于stack exchange,提问作者wehelpdox
相关产品推荐
相关产品推荐

