mirror of
https://github.com/PowerShell/PowerShell
synced 2026-06-08 12:12:50 +00:00
Add '-AsArray' parameter to 'ConvertoTo-Json' command (#6438)
Add `-AsArray` parameter to `ConvertoTo-Json` command to always pack the output string in array brackets, even if the input is a single object.
This commit is contained in:
committed by
Dongbo Wang
parent
cc3ffd8349
commit
dfa11d7f5e
+11
-2
@@ -61,9 +61,18 @@ namespace Microsoft.PowerShell.Commands
|
||||
/// be converted to their string equivalent. Otherwise, enum values
|
||||
/// will be converted to their numeric equivalent.
|
||||
/// </summary>
|
||||
[Parameter()]
|
||||
[Parameter]
|
||||
public SwitchParameter EnumsAsStrings { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the AsArray property.
|
||||
/// If the AsArray property is set to be true, the result JSON string will
|
||||
/// be returned with surrounding '[', ']' chars. Otherwise,
|
||||
/// the array symbols will occur only if there is more than one input object.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public SwitchParameter AsArray { get; set; }
|
||||
|
||||
#endregion parameters
|
||||
|
||||
#region overrides
|
||||
@@ -104,7 +113,7 @@ namespace Microsoft.PowerShell.Commands
|
||||
{
|
||||
if (_inputObjects.Count > 0)
|
||||
{
|
||||
object objectToProcess = (_inputObjects.Count > 1) ? (_inputObjects.ToArray() as object) : (_inputObjects[0]);
|
||||
object objectToProcess = (_inputObjects.Count > 1 || AsArray) ? (_inputObjects.ToArray() as object) : (_inputObjects[0]);
|
||||
// Pre-process the object so that it serializes the same, except that properties whose
|
||||
// values cannot be evaluated are treated as having the value null.
|
||||
object preprocessedObject = null;
|
||||
|
||||
@@ -35,4 +35,17 @@ Describe 'ConvertTo-Json' -tags "CI" {
|
||||
$ps.InvocationStateInfo.State | Should -BeExactly "Stopped"
|
||||
$ps.Dispose()
|
||||
}
|
||||
|
||||
It "The result string is packed in an array symbols when AsArray parameter is used." {
|
||||
$output = 1 | ConvertTo-Json -AsArray
|
||||
$output | Should -BeLike "``[*1*]"
|
||||
|
||||
$output = 1,2 | ConvertTo-Json -AsArray
|
||||
$output | Should -BeLike "``[*1*2*]"
|
||||
}
|
||||
|
||||
It "The result string is not packed in the array symbols when there is only one input object and AsArray parameter is not used." {
|
||||
$output = 1 | ConvertTo-Json
|
||||
$output | Should -BeExactly '1'
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user