Powershell: ConvertTo-Json doesn't serialize $null

Created on 30 Oct 2019  路  5Comments  路  Source: PowerShell/PowerShell

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_).

Steps to reproduce

# 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'

Expected behavior

All tests should pass.

Actual behavior

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]'

Environment data

PowerShell Core 7.0.0-preview.5
Area-Cmdlets-Utility Issue-Question Resolution-Fixed

Most helpful comment

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]'

All 5 comments

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:

Was this page helpful?
0 / 5 - 0 ratings