Conceptually related: #9231
Null values are a legitimate part of JSON, so ConvertTo-Json should be able to serialize them.
Currently, ConvertTo-Json quietly ignores $nulls as a distinct input objects (but does serialize them correctly as a _property values_).
# OK
[pscustomobject] @{ prop=$null } | ConvertTo-Json -Compress | Should -Be '{"prop":null}'
# FAIL
$null | ConvertTo-Json -Compress | Should -Be 'null'
ConvertTo-Json -Compress $null | Should -Be 'null'
All tests should pass.
The $null tests fail:
^ Expected 'null', but got $null
That is, instead of returning string 'null', there was _no output_.
_Update_: To clarify: $null is generally ignored, so the following test fails too, because it returns '[1,2]', not '[1,null,2]':
1, $null, 2 | ConvertTo-Json -Compress | Should -Be '[1,null,2]'
PowerShell Core 7.0.0-preview.5
So you expect: '{"":null}' to come out?
@SteveL-MSFT: No, it should be 'null', as used in the tests.
This should be a fairly simple change, but it also seems like an extreme edge case.
Perhaps a _single_ $null is rare, but what about something like 1, $null, 2 | ConvertTo-Json, which quietly discards the $null?
Consider what JavaScript does:
JSON.stringify(null) -> 'null'
JSON.stringify([1, null, 2]) -> '[1, null, 2]'
:tada:This issue was addressed in #10947, which has now been successfully released as v7.0.0-preview.6.:tada:
Handy links:
Most helpful comment
Perhaps a _single_
$nullis rare, but what about something like1, $null, 2 | ConvertTo-Json, which quietly discards the$null?Consider what JavaScript does:
JSON.stringify(null)->'null'JSON.stringify([1, null, 2])->'[1, null, 2]'