Skip to content

Instantly share code, notes, and snippets.

@bender-the-greatest
Created December 5, 2016 20:18
Show Gist options
  • Save bender-the-greatest/96f616791739c608868e1e7277954f16 to your computer and use it in GitHub Desktop.
Save bender-the-greatest/96f616791739c608868e1e7277954f16 to your computer and use it in GitHub Desktop.
Format-Json Function, allowing to specify the indent level.
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