4

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"}
  ]
}

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately, my powershell version is 2.0(no CoverFrom-Json) and that's the standard for this assignment. (I know it doesn't make sense). Does powershell 2.0 support similar functionality?
@Taewan Not really. There are some different approaches, though. See updated answer.
2

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

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

For example:

PS> $hashtable["key1"]
value1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.