7

I've stumbled across an odd situation in PowerShell 5.1 (Windows 10) where ConvertTo-Json produces {} instead of null for an apparently null valued object:

[CmdletBinding()]
param()
function main() {
    $foo1 = $null
    Write-Verbose ("foo1 null? " + ($null -eq $foo1))
    $foo2 = try{1/0}catch{}
    Write-Verbose ("foo2 null? " + ($null -eq $foo2))
    $foo3 = try{1/0}catch{$null}
    return [PSCustomObject]@{"foo1"=$foo1; "foo2" = $foo2; "foo3" = $foo3} | ConvertTo-Json
}
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
main

Running this cmdlet -verbose shows two apparently $null variables which are serialized differently by ConvertTo-Json:

VERBOSE: foo1 null? True
VERBOSE: foo2 null? True
{
    "foo1":  null,
    "foo2":  {}
    "foo3":  null
}

What is going on here - are there different kinds of $null?

I can't to $foo2 | gm or $foo2.GetType() because $foo2 is null.

mklement0
  • 382,024
  • 64
  • 607
  • 775
Marc
  • 13,011
  • 11
  • 78
  • 98
  • 1
    Yes, there's also an `AutomationNull` – Maximilian Burszley Mar 26 '19 at 15:43
  • FWIW, after this code `(New-Object psobject).GetHashCode() -eq $foo2.PSBase.GetHashCode()` (and `-eq (ConvertFrom-Json "{}").GetHashCode()`). It appears to be a "null object" which compares equal to a proper `$null` reference for most purposes due to eager unwrapping and converting, but is not actually a true, proper `$null`. – Jeroen Mostert Mar 26 '19 at 15:50
  • 2
    Another simple way of getting this object: `$foo2 = &{}`, that is, simply evaluate an empty scriptblock (which is what the `try`/`catch` does in a more roundabout way). It behaves as if it is `$null` in many contexts, but definitely is not `$null`. – Jeroen Mostert Mar 26 '19 at 15:56
  • Indeed, @JeroenMostert; a minimal reproduction is `[pscustomobject] @{ foo = . {}; bar = $null } | ConvertTo-Json` – mklement0 Mar 26 '19 at 18:20
  • It's interesting, though, that `ConvertTo-Json` wouldn't convert `[System.Management.Automation.Internal.AutomationNull]::Value` to `$null`, as that is what usually happens. – mklement0 Mar 26 '19 at 18:23
  • 1
    I've opened a GitHub issue for the unexpected `ConvertTo-Json` behavior: https://github.com/PowerShell/PowerShell/issues/9231 – mklement0 Mar 26 '19 at 18:45

0 Answers0