Powershell: ConvertFrom-Json tolerates non-standard JSON -- consider a -Strict flag

Created on 15 Oct 2020  路  7Comments  路  Source: PowerShell/PowerShell

Steps to reproduce

>"{'key':'value',}" | ConvertFrom-Json

Expected behavior

expecting pwsh to throw an exception just like powershell 5.1

ConvertFrom-Json : Invalid JSON primitive: .
At line:1 char:22
+ "{'key':'value',}" | ConvertFrom-Json
+                      ~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [ConvertFrom-Json], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.ConvertFromJsonCommand

Actual behavior

>"{'key':'value',}" | ConvertFrom-Json

key
---
value

Environment data

Name                           Value
----                           -----
PSVersion                      7.0.3
PSEdition                      Core
GitCommitId                    7.0.3
OS                             Microsoft Windows 10.0.18363
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0鈥
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

I would expect pwsh 7 to throw in this case just like powershell 5.1 does, in a case where I need to pass this json string down to some other tool I can't validate it using pwsh which I was able to do with powershell 5.1, I've laso tried Test-Json which behaves consistently:

> "{'key':'value',}" | Test-Json
True
Area-Cmdlets-Utility Issue-Enhancement Resolution-Duplicate

Most helpful comment

Maybe we should add a '-Strict' flag.

All 7 comments

This is probably due to Newtonsoft.Json being tolerant and not being configured to reject input like this. If we've been permissive like this, it's possible someone now depends on it, but changing it would strike me as a bucket 3 breaking change

We will consider this during migration to the new .Net JSON API.

We will consider this during migration to the new .Net JSON API.

Yeah this is the kind of change that would occur with that migration. In this case I think it's acceptable. Although perhaps in the case of something like comments in the JSON or trailing commas, we might have compatibility issues that we need to investigate.

Maybe we should add a '-Strict' flag.

Duplicate of https://github.com/PowerShell/PowerShell/issues/11117.
Newtonsoft.Json doesn't support trailing comma validation. If we need this, we will have to write a custom JsonTextReader.

Dup #10628

This issue has been marked as duplicate and has not had any activity for 1 day. It has been closed for housekeeping purposes.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

manofspirit picture manofspirit  路  3Comments

SteveL-MSFT picture SteveL-MSFT  路  3Comments

garegin16 picture garegin16  路  3Comments

JohnLBevan picture JohnLBevan  路  3Comments

aragula12 picture aragula12  路  3Comments