Tag Archives: json

Powershell 2.0 Json to Hash

Resonse from webrequests are normally in Json format and converting back and forth is no problem using convertto/from-json. Only this time some computers did run Powershell 2.0 and did not have any “new” .NET framework installed. So I ran to a halt at this Json converting. Since my data did have predefined data structure I thought I could easily do this by some ‘foreach’ and string handling, but it ended up being to complex. Finally I turned my head to regex, this turned out to be the solution.

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
}