我该如何在PowerShell中将以下JSON解析为哈希表?我想要将车名("BMW")作为键,颜色("Dark Gray")作为哈希表的值进行配对。
{
"Car": [
{"BMW": "Dark Gray"},
{"Audi": "Yellow"}
]
}
{
"Car": [
{"BMW": "Dark Gray"},
{"Audi": "Yellow"}
]
}
就像这样:
$json = @'
{
"Car": [
{"BMW": "Dark Gray"},
{"Audi": "Yellow"}
]
}
'@
$ht = @{}
ConvertFrom-Json $json | Select-Object -Expand 'Car' | ForEach-Object {
$ht[$_.PSObject.Properties.Name] = $_.PSObject.Properties.Value
}
如果你被困在PowerShell v2中,但至少拥有.Net Framework 3.5,你可以尝试像这样做:
$json = @'
...
'@
$ht = @{}
[void][Reflection.Assembly]::LoadWithPartialName('System.Web.Extensions')
$serializer = New-Object Web.Script.Serialization.JavaScriptSerializer
$serializer.DeserializeObject($json).Values.GetEnumerator() |
ForEach-Object { $_ } |
ForEach-Object { $ht[($_.Keys -join '')] = ($_.Values -join '') }
$json = @'
...
'@
$ht = @{}
$json -split "`n" | Where-Object {
$_ -match '\{"(.*?)": "(.*?)"\}'
} | ForEach-Object {
$ht[$matches[1]] = $matches[2]
}
$hashtable = '{ "key1":"value1", "key2":"value2" }' | ConvertFrom-Json -AsHashtable
例如:
PS> $hashtable["key1"]
value1