从 JSON 创建哈希表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40495248/
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 18:42:08  来源:igfitidea点击:

Create Hashtable from JSON

jsonpowershell

提问by Marc

I want to get a JSON representation of a Hashtable such as this:

我想获得 Hashtable 的 JSON 表示,例如:

@{Path="C:\temp"; Filter="*.js"}

ConvertTo-Jsonresults in:

ConvertTo-Json结果是:

{
    "Path":  "C:\temp",
    "Filter":  "*.js"
}

However, if you convert that JSON string back with ConvertFrom-Jsonyou don't get a HashTable but a PSCustomObject.

但是,如果您将该 JSON 字符串转换回来,ConvertFrom-Json您将不会得到 HashTable 而是 PSCustomObject。

So how can one reliably serialize the above Hashmap?

那么如何可靠地序列化上述 Hashmap 呢?

回答by sodawillow

$json = @{Path="C:\temp"; Filter="*.js"} | ConvertTo-Json

$hashtable = @{}

(ConvertFrom-Json $json).psobject.properties | Foreach { $hashtable[$_.Name] = $_.Value }

Adapted from PSCustomObject to Hashtable

改编自PSCustomObject 到 Hashtable

回答by wOxxOm

JavaScriptSerializeris available since .NET3.5 (may be installed on XP, included in Win7 and newer), it's several times faster than Convert-FromJSON and it properly parses nested objects, arrays etc.

JavaScriptSerializer从 .NET3.5 开始可用(可能安装在 XP 上,包含在 Win7 和更新版本中),它比 Convert-FromJSON 快几倍,并且可以正确解析嵌套对象、数组等。

function Parse-JsonFile([string]$file) {
    $text = [IO.File]::ReadAllText($file)
    $parser = New-Object Web.Script.Serialization.JavaScriptSerializer
    $parser.MaxJsonLength = $text.length
    Write-Output -NoEnumerate $parser.DeserializeObject($text)
}

回答by ThePoShWolf

A little late to the discussion here, but in PowerShell 6 (Core) there is a -AsHashtableparameter in ConvertFrom-Json.

这里的讨论有点晚了,但在 PowerShell 6(核心)中有一个ConvertFrom-Json-AsHashtable参数。

回答by Esten Rye

The answer for this post is a great start, but is a bit naive when you start getting more complex json representations.

这篇文章的答案是一个很好的开始,但是当您开始获得更复杂的 json 表示时有点天真。

The code below will parse nested json arrays and json objects.

下面的代码将解析嵌套的 json 数组和 json 对象。

[CmdletBinding]
function Get-FromJson
{
    param(
        [Parameter(Mandatory=$true, Position=1)]
        [string]$Path
    )

    function Get-Value {
        param( $value )

        $result = $null
        if ( $value -is [System.Management.Automation.PSCustomObject] )
        {
            Write-Verbose "Get-Value: value is PSCustomObject"
            $result = @{}
            $value.psobject.properties | ForEach-Object { 
                $result[$_.Name] = Get-Value -value $_.Value 
            }
        }
        elseif ($value -is [System.Object[]])
        {
            $list = New-Object System.Collections.ArrayList
            Write-Verbose "Get-Value: value is Array"
            $value | ForEach-Object {
                $list.Add((Get-Value -value $_)) | Out-Null
            }
            $result = $list
        }
        else
        {
            Write-Verbose "Get-Value: value is type: $($value.GetType())"
            $result = $value
        }
        return $result
    }


    if (Test-Path $Path)
    {
        $json = Get-Content $Path -Raw
    }
    else
    {
        $json = '{}'
    }

    $hashtable = Get-Value -value (ConvertFrom-Json $json)

    return $hashtable
}

回答by Gonzalo Contento

I believe the solution presented in Converting JSON to a hashtableis closer to the PowerShell 6.0 implementation of ConvertFrom-Json

我相信Converting JSON to a hashtable 中提出的解决方案更接近ConvertFrom-Json的 PowerShell 6.0 实现

I tried with several JSON sources and I always got the right hashtable.

我尝试了几个 JSON 源,我总是得到正确的哈希表。

$mappings = @{
  Letters = (   
      "A",
      "B")
  Numbers        = (
      "1",
      "2",
      "3")
  Yes = 1
  False = "0"
}

# TO JSON 
$jsonMappings = $mappings  | ConvertTo-JSON
$jsonMappings

# Back to hashtable 
# In PowerShell 6.0 would be:
#   | ConvertFrom-Json -AsHashtable
$jsonMappings | ConvertFrom-Json -As hashtable

回答by Hu Xinlong

you can write a function convert psobject to hashtable.

您可以编写一个函数将 psobject 转换为哈希表。

I wrote a answer here:enter link description here

我在这里写了一个答案:在此处输入链接描述