如何将嵌套JSON转换为powershell中的哈希表?



我正在尝试将JSON转换为Powershell 5.1版本的哈希表。但是输出再次作为FieldMapping Key的对象出现。我们可以得到FieldMapping键的键值对吗?

7.1版本中有ConvertFrom-Json - ashtable。理想情况下,在5.1中也可以获得相同的o/p。接下来我可以尝试什么?

我的json:

$json = '[

{

"EntityType": "IP",

"FieldMapping":  [

{

"ColumnName":  "FileHashCustomEntity"
"Identifier":  "Address"


}

]

}

]'

我的代码:

$entities = $json | ConvertFrom-Json 
$ht2 = @{}
$hash = $entities.psobject.properties | Foreach { $ht2[$_.Name] = $_.Value }
echo $ht2

我输出:

Key   : EntityType
Value : IP
Name  : EntityType

Key   : FieldMapping
Value : {@{ColumnName=FileHashCustomEntity; Identifier=Address}}
Name  : FieldMapping

预期输出:

Key   : EntityType
Value : IP
Name  : EntityType

Key   : FieldMapping
Value : {FileHashCustomEntity}
Name  : FieldMapping

现在您得到的是一个包含自定义对象作为条目的顶级哈希表—您需要做的是将在生成的对象层次中递归地转换每个对象

下面是一个简单的函数:

function Convert-PSCToHashTable
{
param(
$InputObject, 
[int]$Depth = 5
)
if($Depth -gt 0){
if($InputObject -is [System.Collections.IList]){
return @($InputObject |ForEach-Object {Convert-PSCToHashTable $_ -Depth ($Depth - 1)})
}
if($InputObject.psobject.BaseObject -is [System.Management.Automation.PSCustomObject]){
$ht = @{}
foreach($prop in $InputObject.psobject.Properties){
$ht[$prop.Name] = Convert-PSCToHashTable $prop.Value -Depth ($Depth - 1)
}
return $ht
}
}
return $InputObject
}

现在你可以这样做:

$object = ConvertFrom-Json $json
$hashtable = Convert-PSCToHashTable $object
$hashtable['FieldMapping']['ColumnName'] # "FileHashCustomEntity"

可以。包含调试语句,以便您可以查看数据是如何组织的

$json = @" 
[

{

"EntityType": "IP",

"FieldMapping":  [

{

"ColumnName":  "FileHashCustomEntity",
"Identifier":  "Address"


}

]

}

]
"@
$entities = $json | ConvertFrom-Json 
$entities
$ht2 = [System.Collections.ArrayList]::new()
$newRow = New-Object -TypeName psobject
$newRow | Add-Member -NotePropertyName EntityType -NotePropertyValue $entities.EntityType
foreach($property in $entities.FieldMapping)
{
$property | Format-Table
$newRow | Add-Member -NotePropertyName ColumnName -NotePropertyValue $property.ColumnName  
$newRow | Add-Member -NotePropertyName Identifier -NotePropertyValue $property.Identifier

}
$ht2.Add($newRow)  | Out-Null
$ht2 | Format-Table

最新更新