Private/Utils/Format-Json.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
function Format-Json
{
    param
    (
        [Parameter(Mandatory, ValueFromPipeline)
        ][String] $json
    )

    $nl = [Environment]::NewLine

    $indent = 0;
    ($json -Split $nl |
        Foreach-Object {

            if ($_ -match '[\}\]]')
            {
                # This line contains ] or }, decrement the indentation level
                $indent--
            }
            $line = (' ' * $indent * 2) + $_.TrimStart().Replace(': ', ': ')
            if ($_ -match '[\{\[]')
            {
                # This line contains [ or {, increment the indentation level
                $indent++
            }
            $line
        }) -Join $nl
}