Skip to content

Test-Json doesn't recognize JSON arrays or primitives #11384

Closed

Description

Steps to reproduce

'42' | Test-Json | Should -BeTrue
'[ 1, 2 ]' | Test-Json | Should -BeTrue

Expected behavior

The tests should succeed, given that these are valid JSON strings and that piping them to ConvertFrom-Json works just fine:

# These tests pass.
'42' | ConvertFrom-Json | Should -Be 42
'[ 1, 2 ]' | ConvertFrom-Json | Should -Be 1, 2

Actual behavior

Both tests fail.

Environment data

PowerShell Core 7.0.0-rc.1

Activity

  1. added
    Issue-Question
    on Dec 17, 2019
  2. iSazonov commented on Dec 18, 2019

    @iSazonov
    Collaborator

    Michael Klement (@mklement0) Could you please add more info why it should work in the way? Maybe reference to a standard or a quote from the standard. It would help to avoid regressions in follow fix.

  3. mklement0 commented on Dec 18, 2019

    @mklement0
    ContributorAuthor

    Ilya (@iSazonov), I've added a link to json.org to the OP, and also a demonstration that ConvertFrom-Json itself happily accepts such inputs.

  4. iSazonov commented on Dec 18, 2019

    @iSazonov
    Collaborator

    We use NewtonSoft JObject.Parse() which throws. I tried System.Text.Json.JsonDocument.Parse() and … most of our tests failed because examples in the issue and out tests in Test-Json.Tests.ps1 use single quotes but Json standard allows only double quotes.
    So we should decide what to do because switching to JsonDocument.Parse() looks like a breaking change.
    With double quotes the tests and the issue examples are passed if JsonDocument.Parse() is used.

  5. mklement0 commented on Dec 18, 2019

    @mklement0
    ContributorAuthor

    use single quotes but Json standard allows only double quotes.

    The single quotes aren't in the data, they are only there as PowerShell's string delimiter.

    What Test-Json sees is just 42 and [ 1, 2 ] and both are valid JSON strings.

    I haven't looked at the internals, but it's obvious that whatever ConvertFrom-Json manages to parse should be considered valid by Test-Json.

  6. jochenvanwylick commented on Dec 19, 2019

    @jochenvanwylick

    +1 Encountered the same problem here - would love to see this resolved!

  7. iSazonov commented on Dec 19, 2019

    @iSazonov
    Collaborator

    jochenvanwylick You could download artifact from #11397, check your scenarios and report issues there.

  8. mklement0 commented on Dec 19, 2019

    @mklement0
    ContributorAuthor

    Ilya (@iSazonov): In the current implementation,

    should be:

    parsedJson = JToken.Parse(Json);

    Only JToken correctly parses JSON documents such as 42 and [ 1, 2 ], whereas JObject accepts just a single object (dictionary).

    Or, better yet, use the same technique that ConvertFrom-Json uses:

    var obj = JsonConvert.DeserializeObject(
    input,
    new JsonSerializerSettings
    {
    // This TypeNameHandling setting is required to be secure.
    TypeNameHandling = TypeNameHandling.None,
    MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
    MaxDepth = maxDepth
    });

    Note that the code there contains a workaround for a NewtonSoft bug that's no longer needed.


    In a System.Text.Json-based implementation, System.Text.Json.JsonDocument.Parse() is indeed the right tool.


    All these tests succeed:

    # Valid JSON
    '42', '[ 1, 2 ]', '{ "foo": 1 }' | % {
        {  [System.Text.Json.JsonDocument]::Parse($_) } | Should -Not -Throw
        {  [Newtonsoft.Json.Linq.JToken]::Parse($_)  } | Should -Not -Throw
    }
    
    # Invalid JSON
    'a', '[', '{ "foo": 1 }, { "bar": 2 }' | % {
        {  [System.Text.Json.JsonDocument]::Parse($_) } | Should -Throw
        {  [Newtonsoft.Json.Linq.JToken]::Parse($_)  } | Should -Throw
    }
    
  9. iSazonov commented on Dec 19, 2019

    @iSazonov
    Collaborator

    Michael Klement (@mklement0) Thanks! I think we should move to Core API if possible. Sooner or later it will happen anyway. If there are no serious problems, it is better to do it "sooner".

  10. thedavecarroll commented on Mar 11, 2020

    @thedavecarroll

    Has there been any progress on this?

    A Redditor recently made a similar comment. I responded with a link to this issue.

    Basically, I said that they could use ConvertFrom-Json | ConvertTo-Json | Test-Json to perform tests.

    '[ { name : "Joe" } ]' | ConvertFrom-Json | ConvertTo-Json | Test-Json

    Is this the best advice for PowerShell 7 GA?

  11. mklement0 commented on Mar 11, 2020

    @mklement0
    ContributorAuthor

    Dave Carroll (@thedavecarroll), yes, it's unfortunate that this wasn't addressed in time for 7.0

    PR #11397 will implicitly fix these issues, if I understand correctly, but due to its move to a different underlying API it will bring breaking changes, notably no longer being able to use single-quoted JSON (right, Ilya (@iSazonov)?).

    I wasn't even aware of the other issue that Test-Json doesn't support its input as an array of lines, the way ConvertFrom-Json does (e.g., '{ "foo": ', '"bar" }' | Test-Json fails, which succeeds with ConvertFrom-Json)

    As for a workaround: It's sufficient to use only ConvertFrom-Json, and derive from its failure whether the input is valid JSON or not:

    $valid = try { $null = '[ { name : "Joe" } ]' | ConvertFrom-Json; $true } catch { $false }
  12. iSazonov commented on Mar 11, 2020

    @iSazonov
    Collaborator

    Michael Klement (@mklement0) Yes.
    Currently we are waiting .Net 5.0 public preview to continue.

  13. dgard1981 commented on Jul 8, 2020

    @dgard1981

    Might we get another update on this issue?

    Ilya (@iSazonov) said -

    Currently we are waiting .Net 5.0 public preview to continue.

    Looks like this has now happened.

    With regards to suggested workarounds using ConvertFrom-Json - unfortunately that's no good if you are trying to test against a schema.

  14. iSazonov commented on Jul 8, 2020

    @iSazonov
    Collaborator

    We have PRs for ConvertFrom-Json and Test-Json a long time without review. Unfortunately, we missed this time. I think it makes no sense to continue this now. .Net 5 will be frozen soon for release and we have no chance to fix something there if we find problems.

  15. 8 remaining items

  16. JordanTheITGuy commented on Dec 29, 2021

    @JordanTheITGuy

    This is pretty frustrating.

    This basically means that if you want to do anything more complicated than a single object you have to break the array into unique objects, which is terrible from a performance perspective, and otherwise you're stuck with try-catch stuff.

  17. traberc commented on Jan 15, 2022

    @traberc

    I just stumbled across this issue and am baffled that it hasn't been resolved in 2 years, even in the latest versions of PowerShell.

    I am currently running PowerShell 7.2 in Visual Studio Code and Test-Json reports a JSON file is invalid with an array as the root object. Both Visual Studio Code and ConvertFrom-Json treat this file as valid JSON.

    As others have mentioned, regardless of what JSON standard PowerShell is conforming to, Test-Json and ConvertFrom-Json should treat the same input as either valid or invalid JSON. They should not give different results.

    In my case, I can change the schema of my source config file, but that's a lame workaround for a 2-year-old bug.

  18. m-soltani commented on Mar 12, 2022

    @m-soltani

    Really frustrating that this issue still exists. I have exactly a case for which I can not develop a workaround and Test-Json cmdlet should really have this issue fixed.
    Anybody have a working solution when you have to really test against a json schema ?

  19. matyrr-havok commented on Mar 14, 2022

    @matyrr-havok

    If you're desperate, you could try the hacky code in my comment above. It seemed to work OK for a scenario I had.

  20. hilari0n commented on Mar 14, 2022

    @hilari0n

    Yes, this is unbelievable and frustrating, that such a simple and obvious error is still not fixed.
    I ended up writing my own Test-Json script. Unfortunately I can't share it, as it's now the property of my employer.

    Looking at the original code it's not that hard to write your own. You can safely assume, that Newtonsoft.Json and NJsonSchema libraries are present, as PowerShell uses them for this crippled implementation, so they are a mandatory dependency. So you can parse your Json using Newtonsoft.Json, parse your schema using NJsonSchema and do the validation of the first by the second, so using the same libraries the Test-Json command does and probably a similar approach.
    You can add your own features too, e.g. accept Json file paths (not just Json content) and maybe with wildcards, load Json schema indicated in the Json document, provide a way to add PowerShell code validation (e.g. where Json schema can't cover some requirements), change the output format (so you can have results for multiple Json files and it's clear which error is for which document), allow some deserialization options to be set (like max depth, date or number processing), the parsed Json to be returned (so you do not have to parse it separately), etc.
    Most of this can be done while maintaining compatibility with the Test-Json command (i.e. it failing for non-objects), by having the needed behavior work on switches and keeping the default call perform the same crap as Test-Json.

  21. m-soltani commented on Mar 28, 2022

    @m-soltani

    puhh, dont want to waste time, mess around with internals of PowerShell. Found a workaround for this.

  22. eric-ash-1 commented on May 5, 2022

    @eric-ash-1

    I would also love to see this bug fixed. It's still there in 7.2.3

  23. dkaszews commented on Jul 20, 2022

    @dkaszews
    Contributor

    No idea why Ilya (@iSazonov) 's MR was closed, but per Michael Klement (@mklement0) 's suggestion, I just changed the parsedJson from JObject to JToken and everything works with just one line of diff (plus one to remove unnecessary outside declaration):

    -                parsedJson = JObject.Parse(Json);
    +                var parsedJson = JToken.Parse(Json);

    I'll add extra tests and create an MR.

  24. ghost added
    In-PR
    on Jul 21, 2022
  25. ghost removed
    In-PR
    on Jul 25, 2022
  26. ghost added
    Resolution-Fixed
    on Jul 25, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-QuestionResolution-FixedWG-Cmdlets

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions