如何使用 PowerShell 將 JSON 物件轉換為雜湊表格式?
PowerShell 7 支援 ConvertFrom−JSON 命令中的 -AsHashtable 引數,可直接將 JSON 轉換為雜湊表,這是一個非常好的功能。假設我們有以下 JSON 檔案,
我們可以使用管道命令 ConvertFrom−JSON 將 JSON 檔案轉換為自定義表格格式,並使用 −AsHashtable 引數將自定義物件轉換為雜湊表。
PS C:\Temp> Get-Content .\testsevent.json | ConvertFrom-Json -AsHashtable Name Value ---- ----- Events {602d9444−d2cd−49c7−8624−8643e7171297} DocumentIncarnation 0
要檢索資料,
PS C:\Temp> $out = Get−Content .\testsevent.json | ConvertFrom−Json −AsHashtable PS C:\Temp> $out.Events
輸出
PS C:\Temp> $out.Events Name Value ---- ----- Description Host server is undergoing maintenance. EventStatus Scheduled EventId 602d9444−d2cd−49c7−8624−8643e7171297
對於 PowerShell 框架版本,不支援 -AsHashTable 引數,在這種情況下,您需要按如下所示手動將其轉換為雜湊表。
$out = Get−Content .\testsevent.json | ConvertFrom−Json
將 JSON 轉換為雜湊表的程式碼,
$hash = @{} $out.psobject.properties | foreach{$hash[$_.Name]= $_.Value} $hash
輸出
廣告