programing

JSON에서 해시 테이블 생성

newnotes 2023. 4. 5. 22:13
반응형

JSON에서 해시 테이블 생성

다음과 같은 해시 테이블의 JSON 표현을 가져옵니다.

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

ConvertTo-Json결과는 다음과 같습니다.

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

단, JSON 문자열을 변환하여ConvertFrom-JsonHashTable이 아니라 PSCustomObject가 됩니다.

그렇다면 위의 해시맵을 확실하게 시리얼화하려면 어떻게 해야 할까요?

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

$hashtable = @{}

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

PSCustom Object에서 해시 테이블로 변경됨

여기에서는 조금 늦었지만 PowerShell 6(Core)에는-AsHashtableConvert From-Json의 파라미터입니다.

JavaScript Serializer는 에서 사용할 수 있습니다.NET3.5(Windows 7 이후 XP에 설치 가능), Convert-From-J보다 몇 배 빠릅니다.SON은 중첩된 객체, 어레이 등을 적절히 해석합니다.

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)
}

이 투고에 대한 답변은 훌륭한 시작이지만, 좀 더 복잡한 json 표현을 얻기 시작하면 다소 순진합니다.

아래 코드는 중첩된 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
}

JSON을 해시 테이블로 변환에서 제시된 솔루션은 PowerShell 6.0 Convert From-Json 구현에 가깝다고 생각합니다.

여러 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

psobject를 해시 테이블로 변환하는 함수를 쓸 수 있습니다.

여기에 답변을 작성했습니다.링크 설명을 여기에 입력해 주세요.

언급URL : https://stackoverflow.com/questions/40495248/create-hashtable-from-json

반응형