gpt4 book ai didi

.net - 如何在 powershell 中将哈希表转换为 json 字符串?

转载 作者:行者123 更新时间:2023-12-03 07:03:43 27 4
gpt4 key购买 nike

我正在尝试将哈希表转换为 json 对象,以便在带有 powershell 2.0 的 Web 服务中使用。

$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以某种方式应该抑制类型信息,但显然不是。我也对它提取键和值对感到有趣,但我也不希望它这样做。我做错了什么?

最佳答案

好的,manojlds 回答了 v2,所以我将在这里列出 v3 的等效内容:

PS> @{name="oisin"; age=37} | convertto-json
{
"age": 37,
"name": "oisin"
}

相当干净,对吧?

PowerShell 3.0 CTP2:http://www.microsoft.com/download/en/details.aspx?id=27548

关于.net - 如何在 powershell 中将哈希表转换为 json 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8419609/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com