Created
September 29, 2020 23:45
-
-
Save DerekZiemba/4c115226b35e2cea9bb59ec7dcb94a46 to your computer and use it in GitHub Desktop.
Proper Powershell JSON Formatting
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://github.com/PowerShell/PowerShell/issues/2736 | |
# https://github.com/PowerShell/PowerShell/issues/8604 | |
function Format-Json([Parameter(Mandatory, ValueFromPipeline)]$json) { | |
if ($json -isnot [string]) { $json = $json | ConvertTo-Json -Depth 10; } | |
$indent = 0; | |
$lines = $json.Split("`n", [System.StringSplitOptions]::RemoveEmptyEntries); | |
for (($len = $lines.Length), ($i = 0); $i -lt $len; $i++) { | |
$line = $lines[$i]; | |
# This line contains ] or }, decrement the indentation level | |
if (($indent -gt 0) -and ($line -match '[\}\]]')) { $indent -= 2; } | |
$lines[$i] = [string]::Concat([string]::new(' ', $indent), $line.TrimStart().Replace(': ', ': ')); | |
# This line contains [ or {, increment the indentation level | |
if ($line -match '[\{\[]') { $indent += 2; } | |
} | |
$result = [string]::Join("`n", $lines); | |
$result | |
} | |
function Pretty-Json([Parameter(Mandatory, ValueFromPipeline)]$json) { | |
($json | Format-Json).Replace('\\"', "'").Replace('\\', '\') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment