Skip to content

ConvertTo-Json doesn't serialize $null #10942

Closed

Description

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

Activity

  1. added
    Issue-Question
    on Oct 30, 2019
  2. SteveL-MSFT commented on Oct 30, 2019

    @SteveL-MSFT
    Member

    So you expect: '{"":null}' to come out?

  3. mklement0 commented on Oct 30, 2019

    @mklement0
    ContributorAuthor

    Steve Lee (@SteveL-MSFT): No, it should be 'null', as used in the tests.

  4. added
    Up-for-Grabs
    on Oct 30, 2019
  5. SteveL-MSFT commented on Oct 30, 2019

    @SteveL-MSFT
    Member

    This should be a fairly simple change, but it also seems like an extreme edge case.

  6. mklement0 commented on Oct 30, 2019

    @mklement0
    ContributorAuthor

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

  7. removed
    Up-for-Grabs
    on Oct 30, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

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