Skip to content

ConvertFrom-Json returns $null when parsing empty array #16548

Closed

Description

Prerequisites

Steps to reproduce

When using Windows PowerShell 5.1, one can use the ConvertFrom-Json CmdLet to parse JSON strings.
Empty arrays are correctly parsed and return an object that can be piped into the ForEach-Object CmdLet and behaves accordingly.

However, from PowerShell Core 7.x, ConvertFrom-Json now returns a null value when parsing the string "[]".

The FAQ page does not help.

I have not been able to track if that is a desired change from Windows PowerShell 5.1.

I have tested this behavior with:

  • PSCore 7.1.5 stable release.
  • PSCore 7.2.1 stable release.
  • PSCore 7.2.0-daily20211124.2 (daily build)

Expected behavior

PS> (ConvertFrom-JSON "[]").GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

Actual behavior

PS> (ConvertFrom-JSON "[]").GetType()
InvalidOperation: You cannot call a method on a null-valued expression.

Error details

PS> Get-Error
Exception             :
    Type        : System.Management.Automation.RuntimeException
    ErrorRecord :
        Exception             :
            Type    : System.Management.Automation.ParentContainsErrorRecordException
            Message : You cannot call a method on a null-valued expression.
            HResult : -2146233087
        CategoryInfo          : InvalidOperation: (:) [], ParentContainsErrorRecordException
        FullyQualifiedErrorId : InvokeMethodOnNull
        InvocationInfo        :
            ScriptLineNumber : 1
            OffsetInLine     : 1
            HistoryId        : -1
            Line             : (ConvertFrom-JSON "[]").GetType()
            PositionMessage  : At line:1 char:1
                               + (ConvertFrom-JSON "[]").GetType()
                               + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            CommandOrigin    : Internal
        ScriptStackTrace      : at <ScriptBlock>, <No file>: line 1
    TargetSite  : System.Object CallSite.Target(System.Runtime.CompilerServices.Closure, System.Runtime.CompilerServices.CallSite, System.Object)
    Message     : You cannot call a method on a null-valued expression.
    Data        : System.Collections.ListDictionaryInternal
    Source      : Anonymously Hosted DynamicMethods Assembly
    HResult     : -2146233087
    StackTrace  :
   at CallSite.Target(Closure , CallSite , Object )
   at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
   at System.Management.Automation.Interpreter.DynamicInstruction`2.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
CategoryInfo          : InvalidOperation: (:) [], RuntimeException
FullyQualifiedErrorId : InvokeMethodOnNull
InvocationInfo        :
    ScriptLineNumber : 1
    OffsetInLine     : 1
    HistoryId        : -1
    Line             : (ConvertFrom-JSON "[]").GetType()
    PositionMessage  : At line:1 char:1
                       + (ConvertFrom-JSON "[]").GetType()
                       + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    CommandOrigin    : Internal
ScriptStackTrace      : at <ScriptBlock>, <No file>: line 1

Environment data

PS> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      7.2.0-daily20211124.2
PSEdition                      Core
GitCommitId                    7.2.0-daily20211124.2
OS                             Microsoft Windows 10.0.19042
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Visuals

No response

Activity

  1. added
    Needs-Triage
    on Dec 3, 2021
  2. added
    Issue-Question
    on Dec 3, 2021
  3. jborean93 commented on Dec 3, 2021

    @jborean93
    Collaborator

    I believe this is because objects are just enumerated as they appear, because there are no objects (just an empty array) there's nothing to output. You can add -NoEnumerate to have it output objects exactly as they are, similar to how Write-Output -NoEnumerate works.

    See #10861 for the PR that implemented the change the issue linked in it.

  4. iSazonov commented on Dec 3, 2021

    @iSazonov
    Collaborator

    Jordan Borean (@jborean93) No pipeline is in the issue. Expectations here is "[]" -> @().

  5. jborean93 commented on Dec 3, 2021

    @jborean93
    Collaborator

    Yep I understand that but the PR I linked change the behaviour to be what it is today. It acts like outputting an empty array in a function, e.g.

    Function My-Function {
        @()
    }
    
    $obj = My-Function
    $null -eq $obj

    To output the value as is you need to add the -NoEnumerate option, just like you do with Write-Output -NoEnumerate

    Function My-Function {
        # Same as , @() (see the unary comma)
        Write-Output -InputObject @() -NoEnumerate
    }
    
    $obj = My-Function
    $null -ne $ob
    $obj.Count -eq 0
  6. iSazonov commented on Dec 3, 2021

    @iSazonov
    Collaborator

    Jordan Borean (@jborean93) Thanks for clarify!

  7. added
    Resolution-Answered
    on Dec 3, 2021
  8. springcomp commented on Dec 3, 2021

    @springcomp
    Author

    Indeed, Jordan Borean (@jborean93) thanks for the clarification.

  9. ghost removed
    Needs-Triage
    on Dec 3, 2021
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-AnsweredWG-Cmdlets

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions