Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- $script:options = [System.Text.RegularExpressions.RegexOptions]
- $script:OpenMatcher = [regex]::new('[\{\[]\s*$', ($options::Compiled -bor $options::ExplicitCapture))
- function ConvertTo-PrettyJson {
- [CmdletBinding(DefaultParameterSetName="withObject",SupportsShouldProcess=$true)]
- param (
- [parameter(Mandatory,ValueFromPipeline=$true,ParameterSetName="withObject")]
- $InputObject,
- [parameter(Mandatory,ParameterSetName="withJson")]
- [string]
- $Json,
- [ValidateLength(1, 1)]
- [string]
- $IndentChar = ' ',
- [ValidateRange(1, 20)]
- [int]
- $IndentWidth = 4
- )
- switch ($PSCmdlet.ParameterSetName) {
- "withObject" {
- if (! $InputObject) {
- return
- }
- $Json = ConvertTo-Json $InputObject
- }
- "withJson" {
- try {
- $Json = ConvertFrom-Json $Json | ConvertTo-Json $Json
- }
- catch {
- throw 'invalid json format: $Json.'
- }
- }
- }
- if (! $InputObject) { return }
- # unit indent string
- $indent = $IndentChar * $IndentWidth
- # indent stacks for open and close positions
- $indents = @()
- $endIndents = @()
- # current indent
- $lastIndent = -1
- $closeIndent = -1
- # real indent count
- $indentCount = 0
- $Json -split "`r?`n" | ? { $_ } -PipelineVariable line | % {
- $indentSize = $line -match '^ *' | % { $Matches[0].Length }
- switch ($indentSize) {
- $lastIndent {
- # the same indent from previous line
- }
- $closeIndent {
- # parenthesis closed.
- $indents = @($indents | select -Skip 1)
- $endIndents = @($endIndents | select -Skip 1)
- $lastIndent = $indents[0]
- $closeIndent = $endIndents[0]
- $indentCount--
- }
- default {
- # new indent size
- $lastIndent = $indentSize
- $indents = ,$lastIndent + $indents
- }
- }
- # out current line.
- Write-Output (($indent * $indentCount) + $line.Substring($indentSize))
- $match = $script:OpenMatcher.Match($line)
- if ($match.Success) {
- # parenthesis opened.
- $closeIndent = $match.Index
- $endIndents = ,$closeIndent + $endIndents
- $indentCount++
- }
- } | Out-String
- }
Add Comment
Please, Sign In to add comment