Tag Archives: json

PS 2.x convertfrom-json

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
}

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
}