From ec0dba46055e02fd0d554fbc47f4ff18fca7eb9c Mon Sep 17 00:00:00 2001 From: William Easton Date: Mon, 25 Jul 2022 16:14:56 -0500 Subject: [PATCH] Remove pre-parse for array-based JSON (#15684) --- .../commands/utility/WebCmdlet/JsonObject.cs | 16 ---------------- .../ConvertFrom-Json.Tests.ps1 | 10 +++++++++- 2 files changed, 9 insertions(+), 17 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs index 3113dc40d8..8e15615202 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs @@ -160,22 +160,6 @@ namespace Microsoft.PowerShell.Commands error = null; try { - // JsonConvert.DeserializeObject does not throw an exception when an invalid Json array is passed. - // This issue is being tracked by https://github.com/JamesNK/Newtonsoft.Json/issues/1930. - // To work around this, we need to identify when input is a Json array, and then try to parse it via JArray.Parse(). - - // If input starts with '[' (ignoring white spaces). - if (Regex.Match(input, @"^\s*\[").Success) - { - // JArray.Parse() will throw a JsonException if the array is invalid. - // This will be caught by the catch block below, and then throw an - // ArgumentException - this is done to have same behavior as the JavaScriptSerializer. - JArray.Parse(input); - - // Please note that if the Json array is valid, we don't do anything, - // we just continue the deserialization. - } - var obj = JsonConvert.DeserializeObject( input, new JsonSerializerSettings diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertFrom-Json.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertFrom-Json.Tests.ps1 index 135625db98..f03b29e4c8 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertFrom-Json.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertFrom-Json.Tests.ps1 @@ -58,7 +58,15 @@ Describe 'ConvertFrom-Json Unit Tests' -tags "CI" { $json | Should -BeOfType Hashtable } } - + + It 'Throws an ArgumentException with an incomplete array with AsHashtable switch set to ' -TestCase $testCasesWithAndWithoutAsHashtableSwitch { + Param($AsHashtable) + { ConvertFrom-Json '["1",' -AsHashtable:$AsHashtable } | + Should -Throw -ErrorId "System.ArgumentException,Microsoft.PowerShell.Commands.ConvertFromJsonCommand" + { ConvertFrom-Json '[' -AsHashtable:$AsHashtable } | + Should -Throw -ErrorId "System.ArgumentException,Microsoft.PowerShell.Commands.ConvertFromJsonCommand" + } + It 'Can convert multi-line object with AsHashtable switch set to ' -TestCases $testCasesWithAndWithoutAsHashtableSwitch { Param($AsHashtable) $json = @('{"a" :', '"x"}') | ConvertFrom-Json -AsHashtable:$AsHashtable