Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JSON into Hashtable

How do I parse the following JSON into hashtable in PowerShell? I want to pair car name ("BMW") as key and color ("Dark Gray") as value in the hashtable.

{
  "Car": [
    {"BMW": "Dark Gray"},
    {"Audi": "Yellow"}
  ]
}
like image 215
Taewan Avatar asked Sep 10 '25 02:09

Taewan


2 Answers

Like this:

$json = @'
{
  "Car": [
    {"BMW": "Dark Gray"},
    {"Audi": "Yellow"}
  ]
}
'@

$ht = @{}

ConvertFrom-Json $json | Select-Object -Expand 'Car' | ForEach-Object {
    $ht[$_.PSObject.Properties.Name] = $_.PSObject.Properties.Value
}

If you're stuck with PowerShell v2, but have at least .Net Framework 3.5 you could do something like this instead:

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

If that also isn't possible, but your key/value pairs are always on one (separate) line, you could extract the data with a regular expression (although I wouldn't recommend that approach):

$json = @'
...
'@

$ht = @{}

$json -split "`n" | Where-Object {
    $_ -match '\{"(.*?)": "(.*?)"\}'
} | ForEach-Object {
    $ht[$matches[1]] = $matches[2]
}

Otherwise you'll have to write a JSON parser yourself.

like image 126
Ansgar Wiechers Avatar answered Sep 12 '25 19:09

Ansgar Wiechers


In Powershell v6 it's built-in with ConvertFrom-Json:

$hashtable = '{ "key1":"value1", "key2":"value2" }' | ConvertFrom-Json -AsHashtable

For example:

PS> $hashtable["key1"]
value1
like image 45
sheldonzy Avatar answered Sep 12 '25 20:09

sheldonzy