ps/Modules/Alkami.PowerShell.Common/Public/Format-Json.ps1
2023-05-30 22:51:22 -07:00

46 lines
1.3 KiB
PowerShell

function Format-Json {
<#
.SYNOPSIS
Formats JSON in a nicer format than the built-in ConvertTo-Json does.
.PARAMETER json
Can pass in either an object or a string representation of a json object. See examples.
.EXAMPLE
Write-Host ($json | ConvertTo-Json | Format-Json)
.EXAMPLE
Write-Host ($json | Format-Json)
.LINK
https://github.com/PowerShell/PowerShell/issues/2736
#>
param (
[Parameter(Mandatory, ValueFromPipeline)]
[object]$json
)
if ($json.GetType() -ne [string]) {
# Never stop at depth 4 (default) - Max is 100
$json = (ConvertTo-Json -InputObject $json -Depth 100 -Compress:$false)
}
$indent = 0;
$lines = $json -Split '\n'
$newLines = @()
foreach($line in $lines) {
if ($line -match '[\}\]]') {
# This line contains ] or }, decrement the indentation level
$indent--
}
$newLines += (' ' * $indent * 2) + $line.TrimStart().Replace(': ', ': ')
if ($line -match '[\{\[]') {
# This line contains [ or {, increment the indentation level
$indent++
}
}
# the reason for the replaces is because sometimes a comment can just be formatted correctly
return ($newLines -Join "`n").Replace("\u003c","<").Replace("\u003e",">")
}