Windows PowerShell解析JSON:方括号与点语法行为异常疑问
PowerShell 5.1中JSON解析的方括号与点语法问题
问题复现
JSON文件内容(myfile.json)
{ "mykey": "myvalue" }
PowerShell脚本代码
$jsonContent = Get-Content "myfile.json" -Raw | ConvertFrom-Json $jsonContent.GetType().FullName $key = "mykey" Write-Host "Using bracket notation: $($jsonContent[$key])" Write-Host "Using dot notation: $($jsonContent.$key)"
执行输出
System.Management.Automation.PSCustomObject Using bracket notation: Using dot notation: myvalue
原因解释
你遇到的问题核心是PowerShell 5.1中ConvertFrom-Json返回的PSCustomObject类型,语法规则和你预期的哈希表不同:
- 点语法生效:
PSCustomObject原生支持通过.访问属性,不管属性名是硬编码还是通过变量($jsonContent.$key),只要变量对应属性存在就能正常取值。 - 方括号语法失效:在
PSCustomObject上,方括号是用来索引集合元素(比如数组、列表)的语法,而非访问对象属性。直接用$jsonContent[$key]会返回空值,因为它把$key当成了集合的索引位置,但PSCustomObject并不是集合类型。
替代解决方案
如果想通过变量名用类似方括号的方式访问属性,有两种可行方法:
- 利用
PSObject的属性集合:
$jsonContent.PSObject.Properties[$key].Value
- 将
PSCustomObject转换为哈希表(PowerShell 5.1无内置转换命令,需自行实现):
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 } } } $hashContent = $jsonContent | ConvertTo-Hashtable Write-Host "Hashtable bracket notation: $($hashContent[$key])"
内容的提问来源于stack exchange,提问作者Giacomo Pirinoli
相关产品推荐
相关产品推荐

