我試圖將哈希錶轉換爲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但它顯然不是。我也很喜歡它提取鍵和值對,但我希望它不這樣做。我究竟做錯了什麼?
這看起來像是序列化功能應該在它自己的事,不是嗎?無論哪種方式 - 這種方式幾乎完美 - 在兩層嵌套散列上失敗。 – reconbot
@wizard - 它應該是我認爲簡單的哈希表。你可以看看aroudn,已經有腳本像我已經鏈接到JSON解析。 – manojlds
我結束了使用http://poshcode.org/2930有問題,但工作得不錯 - 有一天PowerShell 3.0將可用,我會回顧這些浪費的時間,並感到沮喪 – reconbot