powershell递归将json转换为hashtable

时间:2018-10-17 15:25:00

标签: json powershell hashtable

我需要使用PowerShell将JSON文件转换为哈希表。我读取json文件,将其内容转换为对象,然后尝试创建一种方法,该方法应解析powershell对象并将其转换为hashtable,该值不能为hashtables或自定义对象。 JSON的示例:

{
  "obj": {
    "field1" : "value1",
    "field2": {
      "field3": "value3",
      "field4": "hello, world!"
    }
  },
  "other": "abcde"
}

我应该得到一个哈希表,其中包含所有字符串类型的键。因此,结果应为:

Name               | Value
obj.field1         | value1
obj.field2.field3  | value3
obj.field2.field4  | hello, world!
obj.other          | abcde

试图使用某些递归,但它不起作用。代码我有:

function Get-AxJsonNodesList
{
param
(
    [Parameter(Mandatory = $true)]
    [ValidateNotNullOrEmpty()]
    [string]$fileName
)

function ConvertTo-Hashtable
{
    [OutputType("hashtable")]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$JsonContent,
        [Parameter(Mandatory = $true)]
        [AllowEmptyString()]
        [string]$JsonContentKey,
        [Parameter(Mandatory = $true)]
        [ValidateNotNull()]
        [AllowEmptyString()]
        [string]$Parent
    )

    function Merge-HashTables 
    { 
        param 
        ( 
            [Parameter(Mandatory = $true)] 
            [ValidateNotNull()] 
            [hashtable]$left, 
            [Parameter(Mandatory = $true)] 
            [ValidateNotNull()] 
            [hashtable]$right 
        ) 
        $merged = @{} 
        foreach ($key in $left.keys) 
        { 
            $merged.add($key, $left[$key]) 
        } 
        foreach ($key in $right.keys) 
        { 
            $merged.add($key, $right[$key]) 
        } 
        $merged 
    } 

    if ($jsonContent -eq $null)
    {
        return $null
    }
    $result = @{}
    $p = $parent + $(if ($parent -eq "") { "" } else { "." })
    if ($JsonContent -is [System.Collections.IEnumerable] -and $JsonContent -isnot [string])
    {
        foreach ($objectKey in $JsonContent.Keys)
        {
            $hashTableToAdd = ConvertTo-Hashtable -JsonContent $JsonContent[$objectKey] -JsonContentKey $objectKey -Parent $p
            $result = Merge-HashTables $result $hashTableToAdd
        }
    }
    elseif ($JsonContent -is [PSObject])
    {
        foreach ($property in $JsonContent.PSObject.Properties)
        {
            $hashTableToAdd = ConvertTo-Hashtable -JsonContent $property.Value -JsonContentKey $property.Value -Parent $p
            $result = Merge-HashTables $result $hashTableToAdd
        }
    }
    else
    {
        $result[$p + $JsonContentKey] = $JsonContent
    }
    $result
}

ConvertTo-Hashtable (Get-Content $fileName | ConvertFrom-Json) "" ""
}

0 个答案:

没有答案