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
相关产品推荐
相关产品推荐

