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

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并不是集合类型。

替代解决方案

如果想通过变量名用类似方括号的方式访问属性,有两种可行方法:

  1. 利用PSObject的属性集合:
$jsonContent.PSObject.Properties[$key].Value
  1. 将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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 19:52:45