代码
我有以下脚本,主要基于此网站上的信息:
cls
if ($PSVersionTable.PSVersion.Major -lt 3) {
function ConvertTo-Json([psobject] $item){
[System.Reflection.Assembly]::LoadWithPartialName("System.Web.Extensions") | out-null
$ser = New-Object System.Web.Script.Serialization.JavaScriptSerializer
$hashed = @{}
$item.psobject.properties | %{ $hashed.($_.Name) = $_.Value }
write-output $ser.Serialize($hashed)
}
function ConvertFrom-Json([string] $json){
[System.Reflection.Assembly]::LoadWithPartialName("System.Web.Extensions") | out-null
$ser = New-Object System.Web.Script.Serialization.JavaScriptSerializer
write-output (new-object -type PSObject -property $ser.DeserializeObject($json))
}
}
$jsonObj = (new-object -type psobject -property @{
MyDummyData = @{
Version = '1.0.4'
CreationDate = ("{0:yyyy-MM-ddTHH:mm:ss.fffZ}" -f ((Get-Date).ToUniversalTime()))
Demo = 'hello'
Recurse = @{
Hello = "hi"
Greetings = @{
what = "now"
}
}
}
})
"`n`nobj"
$jsonObj
"`n`nobj to json"
$jsonx = ConvertTo-Json($jsonObj)
$jsonx
"`n`njson to obj"
$x = ConvertFrom-Json($jsonx)
$x
"Compare"
$x -eq $jsonObj
输出
obj
MyDummyData
-----------
{Version, Demo, CreationDate, Recurse}
obj to json
{"MyDummyData":{"Version":"1.0.4","Demo":"hello","CreationDate":"2015-07-23T18:
59:04.265Z","Recurse":{"Greetings":{"what":"now"},"Hello":"hi"}}}
json to obj
{[Version, 1.0.4], [Demo, hello], [CreationDate, 2015-07-23T18:59:04.265Z], ...
Compare
False
问题
当我测试时ConvertTo-Json
完美无缺。
但是ConvertFrom-Json
没有解析为我开始使用的对象,而是给了一个包含许多名称 - 值对的对象。
问题
任何人都可以发现我错过的东西;或者这里提出的方法是否仅适用于某些情况?
相关
现有答案示例:PowerShell 2.0 ConvertFrom-Json and ConvertTo-Json implementation