PowerShell 2.0 ConvertFrom-Json 和 ConvertTo-Json 实现

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28077854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:43:01  来源:igfitidea点击:

PowerShell 2.0 ConvertFrom-Json and ConvertTo-Json implementation

jsonpowershellpowershell-2.0

提问by Josh Petitt

I would like to monkeypatch a PowerShell 2.0 environment where the upgrade to 3.0 is not possible at this time.

我想对目前无法升级到 3.0 的 PowerShell 2.0 环境进行猴子补丁。

I am looking for a PowerShell 2.0 script implementation of the ConvertFrom-Jsoncmdlet and ConvertTo-Jsoncmdlet that are in PowerShell 3.0.

我正在寻找PowerShell 3.0 中ConvertFrom-Jsoncmdlet 和ConvertTo-Jsoncmdlet的 PowerShell 2.0 脚本实现。

I am most interested in the ConvertFrom-Json, but ConvertTo-Jsonwould also be nice.

我对 最感兴趣ConvertFrom-Json,但ConvertTo-Json也会很好。

回答by Edward

function ConvertTo-Json20([object] $item){
    add-type -assembly system.web.extensions
    $ps_js=new-object system.web.script.serialization.javascriptSerializer
    return $ps_js.Serialize($item)
}

function ConvertFrom-Json20([object] $item){ 
    add-type -assembly system.web.extensions
    $ps_js=new-object system.web.script.serialization.javascriptSerializer

    #The comma operator is the array construction operator in PowerShell
    return ,$ps_js.DeserializeObject($item)
}

回答by cdoughty

I'm unable to comment on the currently top rated post above, however you can run these registry commands (more details):

我无法对上面当前评价最高的帖子发表评论,但是您可以运行这些注册表命令(更多详细信息):

   reg add hklm\software\microsoft\.netframework /v OnlyUseLatestCLR /t REG_DWORD /d 1 /f
   reg add hklm\software\wow6432node\microsoft\.netframework /v OnlyUseLatestCLR /t REG_DWORD /d 1 /f

to allow the above ConvertTo-Json20and ConvertTo-Json20functions to work if you're getting the error:

如果您收到错误,则允许上述ConvertTo-Json20ConvertTo-Json20功能正常工作:

Add-Type : Could not load file or assembly 'System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 or one of its dependencies. The system cannot find the file specified. "

回答by Artem Mikryukov

Code with javascriptSerializer return objects with Dictionary inside. Modern convertfrom-JSON (4.0+) return objects only. This code transform deserialize object to modern output :)

带有 javascriptSerializer 的代码返回带有 Dictionary 的对象。现代 convertfrom-JSON (4.0+) 仅返回对象。此代码将对象反序列化为现代输出:)

function Iterate-Tree($jsonTree) {
    $result = @()
    foreach ($node in $jsonTree) {
        $nodeObj = New-Object psobject
        foreach ($property in $node.Keys) {
            if ($node[$property] -is [System.Collections.Generic.Dictionary[String, Object]] -or $node[$property] -is [Object[]]) {
                $inner = @()
                $inner += Iterate-Tree $node[$property]
                $nodeObj  | Add-Member -MemberType NoteProperty -Name $property -Value $inner
            } else {
                $nodeObj  | Add-Member -MemberType NoteProperty -Name $property -Value $node[$property]
                #$nodeHash.Add($property, $node[$property])
            }
        }
        $result += $nodeObj
    }
    return $result
}

function ConvertFrom-Json20{ 
    [cmdletbinding()]
    Param (
        [parameter(ValueFromPipeline=$true)][object] $PS_Object
    )

    add-type -assembly system.web.extensions
    $PS_JavascriptSerializer=new-object system.web.script.serialization.javascriptSerializer
    $PS_DeserializeObject = ,$PS_JavascriptSerializer.DeserializeObject($PS_Object) 

    #Convert Dictionary to Objects
    $PS_DeserializeObject = Iterate-Tree $PS_DeserializeObject

    return $PS_DeserializeObject
}

回答by Sean Bulger

I am unable to comment on Edward's answer above. I know this question is older and most people have moved on from it, but I just spent a good amount of time trying to correct the issue seen by other users when using the ConvertTo-JSON20 above.

我无法评论爱德华在上面的回答。我知道这个问题已经很老了,大多数人已经离开了它,但我只是花了很多时间试图纠正其他用户在使用上面的 ConvertTo-JSON20 时看到的问题。

I was receiving the error below when trying to update a list of sites from a JSON file to an updated list.

尝试将站点列表从 JSON 文件更新为更新列表时,我收到以下错误。

"Exception calling "Serialize" with "1" argument(s): "A circular reference was detected while serializing an object of type 'System.Management.Automation.PSMethod'"

“使用“1”个参数调用“Serialize”的异常:“在序列化'System.Management.Automation.PSMethod'类型的对象时检测到循环引用”

When I cast the array by using $array = @() it creates the array as a generic Object[], however, if you explicitly cast the array as a string (by using [string[]]$array = @() ConvertTo-JSON20 is able to convert the string to JSON.

当我使用 $array = @() 转换数组时,它会将数组创建为通用 Object[],但是,如果您将数组显式转换为字符串(通过使用 [string[]]$array = @() ConvertTo -JSON20 能够将字符串转换为 JSON。