mkht / pspm

PowerShell Package Manager
MIT License
13 stars 1 forks source link

There is a potential bug in the Format-Json function. #74

Closed mkht closed 4 years ago

mkht commented 4 years ago

ArgumentOutOfRangeException will be raised when executing Format-Json on a JSON with an array value that contains a mixture of literal and hash values.

Notes 1.

This issue was reported by @vody. Thank you very much !

Notes 2.

This is a potential issue in a private function and does not affect the operation of pspm.

Example Json:

{
  "key": [
    "Literal Value 1",
    {
      "John": "American",
      "Allen": "Italy",
      "Kojima": "Japanese"
    },
    "Literal Value 2"
  ]
}

Expected behavior

$json = Get-Content example.json
$json | Format-Json
{
  "key": [
    "Literal Value 1",
    {
      "John": "American",
      "Allen": "Italy",
      "Kojima": "Japanese"
    },
    "Literal Value 2"
  ]
}

Actual behavior

$json = Get-Content example.json
$json | Format-Json
Specified argument was out of the range of valid values.
Parameter name: times
At line:19 char:13
+             $line = (' ' * $indent * 2) + $_.TrimStart().Replace(':   ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], ArgumentOutOfRangeExce 
   ption
    + FullyQualifiedErrorId : System.ArgumentOutOfRangeException

Work Around

1. Reads JSON as a string literal

$json = Get-Content example.json -Raw
$json | Format-Json
mkht commented 4 years ago

Even a minified JSON, A problem happens and this cannot be avoided with workaround 1.

$MinJson = '{"key":["Literal Value 1",{"John":"American","Allen":"Italy","Kojima":"Japanese"},"Literal Value 2"]}'
$json | Format-Json
Specified argument was out of the range of valid values.
Parameter name: times
At line:19 char:13
+             $line = (' ' * $indent * 2) + $_.TrimStart().Replace(':   ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], ArgumentOutOfRangeExce 
   ption
    + FullyQualifiedErrorId : System.ArgumentOutOfRangeException