Powershell 2 does not have a convertfrom-json function and I like to use json files for storing configuration. Searching the web gives almost zero results. Converting a multilevel json structure to hashtable would be very complicated. Since my config files are only one level the easiest way of doing it was using regex. Input is json structure and output is an hashtable.
function convertfrom-json-onelevel {
Param (
[string[]] $json
)
$hashtable = @{ }
$t = $json | Select-String -Pattern '(["])(?:(?=(\\?))\2.)*?\1' -AllMatches
$hashtable = @{ }
(0..((($t.matches).count - 1) / 2)) | % {
$key = [regex]::Unescape($t.Matches[$_ * 2].Value)
$key = $key.TrimEnd('"')
$key = $key.TrimStart('"')
$value = [regex]::Unescape($t.Matches[$_ * 2 + 1].Value)
$value = $value.TrimEnd('"')
$value = $value.TrimStart('"')
$hashtable.add($key, $value)
}
return $hashtable
}