From 211010ff68136bb4d2692ccb3df8d2bd1e81ded0 Mon Sep 17 00:00:00 2001 From: mkht Date: Sun, 12 Apr 2020 20:03:25 +0900 Subject: [PATCH] Fix Format-Json potential issues #74 --- functions/Format-Json.ps1 | 51 +++++++++++++++++++++++++-------------- 1 file changed, 33 insertions(+), 18 deletions(-) diff --git a/functions/Format-Json.ps1 b/functions/Format-Json.ps1 index d8d3b9c..e69d439 100644 --- a/functions/Format-Json.ps1 +++ b/functions/Format-Json.ps1 @@ -2,28 +2,43 @@ # Formats JSON in a nicer format than the built-in ConvertTo-Json does. function Format-Json { + [CmdletBinding()] param ( [Parameter(Mandatory, ValueFromPipeline)] - [String] - $json + [string] + $InputObject ) + Begin { + $Buffer = New-Object 'System.Collections.Generic.List[string]' + } - $indent = 0; - $result = ($json -Split '\n' | - % { - if ($_ -match '^\s*[\}\]]') { - # This line contains ] or }, decrement the indentation level - $indent-- - } - $line = (' ' * $indent * 2) + $_.TrimStart().Replace(': ', ': ') - if ($_ -match '[\[\{](?!(.*[\{\[\"]))') { - # This line contains [ or {, increment the indentation level - $indent++ - } - $line - }) -Join "`n" + Process { + $Buffer.Add($InputObject) + } - # Unescape Html characters (<>&') - $result.Replace('\u0027', "'").Replace('\u003c', "<").Replace('\u003e', ">").Replace('\u0026', "&") + End { + $json = [string]::Join("`n", $Buffer.ToArray()) + + [int]$indent = 0; + $result = ($json -Split '\n' | + % { + if ($_ -match '^\s*[\}\]]') { + # This line contains ] or }, decrement the indentation level + if (--$indent -lt 0) { + #fail safe + $indent = 0 + } + } + $line = (' ' * $indent * 2) + $_.TrimStart().Replace(': ', ': ') + if ($_ -match '[\[\{](?!(.*[\{\[\"]))') { + # This line contains [ or {, increment the indentation level + $indent++ + } + $line + }) -Join "`n" + + # Unescape Html characters (<>&') + $result.Replace('\u0027', "'").Replace('\u003c', "<").Replace('\u003e', ">").Replace('\u0026', "&") + } }