2011-12-07 42 views
5

我試圖將哈希錶轉換爲json對象,以便在使用PowerShell 2.0的Web服務中使用。如何將powershell中的hastable轉換爲json字符串?

$testhash = @{ 
    Name = 'John Doe' 
    Age = 10 
    Amount = 10.1 
    MixedItems = (1,2,3,"a") 
    NestedHash = @{ 
     nestedkey = "nextedvalue" 
    } 
} 

function toJson($obj){ 

    $ms = New-Object IO.MemoryStream 
    $type = $obj.getType() 
    [Type[]]$types = ($obj | select -expand PsTypeNames | Select -unique) + [type]'System.Management.Automation.PSObject' 
    $js = New-Object System.Runtime.Serialization.Json.DataContractJsonSerializer $type, $types, ([int]::MaxValue), $false, $null, $false 
    $js.writeObject($ms, $obj) | out-null 
    $utf8.GetString($ms.ToArray(), 0, $ms.Length) 
    $ms.Dispose() | out-null 
} 

toJson $testhash 
'[{"Key":"Name","Value":"John Doe"},{"Key":"Age","Value":10},{"Key":"Amount","Value":10.1},{"Key":"NestedHash","Value":[{"__type":"KeyValuePairOfanyTypeanyType:#System.Collections.Generic","key":"nestedkey","value":"nextedvalue"}]},{"Key":"MixedItems","Value":[1,2,3,"a"]}]' 

我使用的應該抑制類型信息的方式DataContractJsonSerializer constructor但它顯然不是。我也很喜歡它提取鍵和值對,但我希望它不這樣做。我究竟做錯了什麼?

回答

3

我從here如下改編劇本:

$testhash = @{ 
    Name = 'John Doe' 
    Age = 10 
    Amount = 10.1 
    MixedItems = (1,2,3,"a") 
    NestedHash = @{ 
     nestedkey = "nextedvalue" 
    } 
} 

function Read-Stream { 
PARAM(
    [Parameter(Position=0,ValueFromPipeline=$true)]$Stream 
) 
process { 
    $bytes = $Stream.ToArray() 
    [System.Text.Encoding]::UTF8.GetString($bytes,0,$bytes.Length) 
}} 

function New-Json { 
[CmdletBinding()] 
param([Parameter(ValueFromPipeline=$true)][HashTable]$InputObject) 
begin { 
    $ser = @{} 
    $jsona = @() 
} 
process { 
    $jsoni = 
    foreach($input in $InputObject.GetEnumerator() | Where { $_.Value }) { 
     if($input.Value -is [Hashtable]) { 
     '"'+$input.Key+'": ' + (New-JSon $input.Value) 
     } else { 
     $type = $input.Value.GetType() 
     if(!$Ser.ContainsKey($Type)) { 
      $Ser.($Type) = New-Object System.Runtime.Serialization.Json.DataContractJsonSerializer $type 
     } 
     $stream = New-Object System.IO.MemoryStream 
     $Ser.($Type).WriteObject($stream, $Input.Value) 
     '"'+$input.Key+'": ' + (Read-Stream $stream) 
     } 
    } 

    $jsona += "{`n" +($jsoni -join ",`n")+ "`n}" 
} 
end { 
    if($jsona.Count -gt 1) { 
     "[$($jsona -join ",`n")]" 
    } else { 
     $jsona 
    } 
}} 

$testHash | New-Json 
+0

這看起來像是序列化功能應該在它自己的事,不是嗎?無論哪種方式 - 這種方式幾乎完美 - 在兩層嵌套散列上失敗。 – reconbot

+0

@wizard - 它應該是我認爲簡單的哈希表。你可以看看aroudn,已經有腳本像我已經鏈接到JSON解析。 – manojlds

+0

我結束了使用http://poshcode.org/2930有問題,但工作得不錯 - 有一天PowerShell 3.0將可用,我會回顧這些浪費的時間,並感到沮喪 – reconbot

相關問題