Skip to content

Instantly share code, notes, and snippets.

@DerekZiemba
Created September 29, 2020 23:45
Show Gist options
  • Save DerekZiemba/4c115226b35e2cea9bb59ec7dcb94a46 to your computer and use it in GitHub Desktop.
Save DerekZiemba/4c115226b35e2cea9bb59ec7dcb94a46 to your computer and use it in GitHub Desktop.
Proper Powershell JSON Formatting
# 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