Created
December 5, 2016 20:18
-
-
Save bender-the-greatest/96f616791739c608868e1e7277954f16 to your computer and use it in GitHub Desktop.
Format-Json Function, allowing to specify the indent level.
This file contains 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
function Format-Json { | |
Param( | |
[Parameter(ValueFromPipeline=$True,Mandatory=$True)] | |
[string]$jsondata, | |
[int]$indent=2 | |
) | |
# Processing blocks are useful for multiline JSON strings | |
begin { $fullpipeline = "" } | |
process { $fullpipeline += $jsondata } | |
end { | |
$jsonformatted += $fullpipeline | ConvertFrom-Json | ConvertTo-Json | |
# ConvertTo-Json doesn't have an indentation parameter, so do it ourselves | |
$nested = 1 | |
($jsonformatted -split '\r\n' | | |
% { | |
$line = $_ | |
if ($_ -match '^ +') { | |
$length = $indent * $nested | |
$line = ' ' * $length + $_.TrimStart() | |
# Determine the nesting of the next line | |
if ($_ -match '^*[\{|\[]$') { | |
$nested++ | |
} elseif ($_ -match '^*[\}|\]]$') { | |
$nested-- | |
} | |
} | |
Write-Output $line | |
} | |
) -join "`r`n" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment