Instantly share code, notes, and snippets.

Embed
What would you like to do?
Write a Json object in human readable format. The `$json` parameter expects a Json object, returned from `ConvertFrom-Json`. More Info: http://blog.vertigion.com/post/94476016067/powershell-write-json
function Write-Json {
param(
[Parameter(
Mandatory=$true,
HelpMessage = "Json object to be printed out in human readable format."
)][PSCustomObject]$Json,
[int]$tab=1,
[bool]$array=$false
)
Write-Debug @"
Write-Json >
Json [$($Json.GetType())]: $Json
tab: $tab
"@
function __write($type, $key, $value, $tab, $fromarray=$false) {
Write-Verbose "~~${key} [$type]: $value"
Write-Verbose "TAB:$(__tabs $tab)$tab"
if ($type -eq 'System.Management.Automation.PSCustomObject') {
$t = $tab+1
Write-Verbose "++Tab Adjust: $tab > $t"
if ($fromarray) {
return "$(__tabs $tab)$(Write-Json -tab ${t} $value),`n"
} else {
return "$(__tabs $tab)""$key"": $(Write-Json -tab ${t} $value),`n"
}
} elseif ($type -eq 'System.Object[]') {
$key = [regex]::replace($key, '=[^=]+$', '')
$t = $tab+1
Write-Verbose "++Tab Adjust: $tab > $t"
if ($fromarray) {
return "$(__tabs $tab)$(Write-Json -tab ${t} -array $true $value),`n"
} else {
return "$(__tabs $tab)""$key"": $(Write-Json -tab ${t} -array $true $value),`n"
}
} elseif (($type -eq 'System.Int32') -or ($type -eq 'int')) {
if ($fromarray) {
return "$(__tabs $tab)$value,`n"
} else {
return "$(__tabs $tab)""$key"": $value,`n"
}
} else {
if ($fromarray) {
return "$(__tabs $tab)""$value"",`n"
} else {
return "$(__tabs $tab)""$key"": ""$value"",`n"
}
}
}
function __tabs($cnt) {
$i=0
$tabs=''
While ($i -lt $cnt) {
$tabs += "`t"
$i=$i+1
}
return $tabs
}
$i=1; Do { $tabs += "`t``"; $i=$i+1 } While ($i -lt $tab)
$ret = if ($array) { "[`n" } else { "{`n" }
if ("$($Json.GetType())" -eq 'System.Object[]') {
foreach ($v in $Json) {
Write-Verbose "loop: $v"
$type = "$($v.GetType())"
$value = $v
Write-Verbose "TAB1:$(__tabs $tab)$tab"
$ret += __write $type -value $value -tab $tab -fromarray $true
Write-Verbose "TAB2:$(__tabs $tab)$tab"
}
} else {
$Json | ForEach-Object {
foreach ($property in ($_ | Get-Member -MemberType NoteProperty)) {
Write-Verbose "loop: $($property.Definition)"
$type = [regex]::matches($property.Definition, '(^\S+)').Captures.Value
$value = $_.$($property.Name)
$key = [regex]::replace($property.Definition.Replace("=${value}",''), '^\S+\s+', '')
Write-Verbose "TAB3:$(__tabs $tab)$tab"
$ret += __write $type $key $value $tab
Write-Verbose "TAB4:$(__tabs $tab)$tab"
}
}
}
# $i=1; $tabs=''; While ($i -lt $tab) { $tabs += "`t``"; $i=$i+1 }
$close = if ($array) { "]" } else { "}" }
return $([regex]::replace($ret, ",`n$", "`n")) + "$(__tabs $($tab-1))${close}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment