Skip to content

Commit

Permalink
Fix Format-Json potential issues #74
Browse files Browse the repository at this point in the history
  • Loading branch information
mkht committed Apr 12, 2020
1 parent 2c5fdb4 commit 211010f
Showing 1 changed file with 33 additions and 18 deletions.
51 changes: 33 additions & 18 deletions functions/Format-Json.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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', "&")
}
}

0 comments on commit 211010f

Please sign in to comment.