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

PowerShell中获取JSON嵌套哈希表各级键名的实现问题

PowerShell读取JSON并输出指定键名解决方案

需求

读取abc.json文件,输出其中testCases及其子节点test-1、test-2的键名。

abc.json内容

{
  "testCases": {
    "test-1": {
      "some-path": "https://",
      "folders": {
        "sample": {
          "files": "abc"
        }
      }
    },
    "test-2": {
      "some-path": "https://",
      "folders": {
        "sample": {
          "files": "def"
        }
      }
    }
  }
}

问题现状

尝试的代码仅能输出顶层键testCases,无法获取其子节点test-1、test-2的键名。原尝试代码:

# Reading the abc.json file
$changesJsonData = Get-Content abc.json -Raw | ConvertFrom-Json

# Convert the PSCustomObject back to a hashtable
$ht2 = @{}
$changesJsonData.psobject.properties | Foreach { $ht2[$_.Name] = $_.Value}
Write-Output $ht2.Keys
foreach($testNames in $ht2.Values){
Write-Output $ht2.Key
}

当前输出:

testCases

期望输出:

testCases
test-1
test-2

解决方法

方法一:直接操作PSCustomObject(推荐)

ConvertFrom-Json返回的PSCustomObject可通过.psobject.properties.Name直接获取属性名(对应JSON的键),无需转换为哈希表:

# 读取并转换JSON文件
$jsonData = Get-Content abc.json -Raw | ConvertFrom-Json

# 输出顶层键
Write-Output "testCases"

# 获取testCases的子键并输出
$jsonData.testCases.psobject.properties.Name | Write-Output

方法二:修正哈希表转换后的逻辑

如果坚持使用哈希表,需要修正循环内的输出逻辑,遍历testCases对应的哈希表并输出其键:

# 读取并转换JSON文件
$changesJsonData = Get-Content abc.json -Raw | ConvertFrom-Json

# 将顶层对象转为哈希表
$ht2 = @{}
$changesJsonData.psobject.properties | ForEach-Object { $ht2[$_.Name] = $_.Value }

# 输出顶层键
Write-Output $ht2.Keys

# 遍历testCases对应的哈希表,输出子键
foreach ($testCase in $ht2.Values) {
    $testCase.Keys | Write-Output
}

两种方法均可得到期望的输出结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 04:37:47