Powershell: ConvertTo-Json -AsArray should be an array "guarantor", not a constructor

Created on 31 Oct 2019  路  1Comment  路  Source: PowerShell/PowerShell

When I originally wrote up the proposal for -AsArray in #6327, I meant it to work like @(...):

That is, the input should be converted to an array (and serialized as such) _unless it already is one_.

Instead, -AsArray, as currently implemented, _unconditionally_ treats the input as an array.

With _pipeline_ input, which automatically gets enumerated, that usually makes no difference, but it does when you pass the inputs as an _argument_.

Steps to reproduce

ConvertTo-Json -AsArray 1 -Compress | Should -Be '[1]'
ConvertTo-Json -AsArray 1,2 -Compress | Should -Be '[1,2]'
ConvertTo-Json -AsArray @() -Compress | Should -Be '[]'

Expected behavior

All tests should pass.

Actual behavior

The last 2 tests fail, because they wrap the already array-valued input in an _extra_ array:

Expected length: 5 Actual length:   7 Strings differ at index 1. 
Expected: '[1,2]'
But was:  '[[1,2]]'

Expected length: 5 Actual length:   7 Strings differ at index 1. 
Expected: '[]'
But was:  '[[]]'

Environment data

PowerShell Core 7.0.0-preview.5
Area-Cmdlets-Utility Breaking-Change Issue-Question

Most helpful comment

This is a breaking change, but it seems unlikely anyone would want the current behavior.

>All comments

This is a breaking change, but it seems unlikely anyone would want the current behavior.

Was this page helpful?
0 / 5 - 0 ratings