Search code examples
jsonparsingpowershellhashtable

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

Solution

  • 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.