Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using System;
using System.Collections.Generic;
using System.Management.Automation;
using System.Reflection;

namespace Microsoft.PowerShell.Commands
{
Expand Down Expand Up @@ -43,6 +42,13 @@ public class ConvertFromJsonCommand : Cmdlet
[ValidateRange(ValidateRangeKind.Positive)]
public int Depth { get; set; } = 1024;

/// <summary>
/// Gets or sets the switch to prevent ConvertFrom-Json from unravelling collections during deserialization, instead passing them as a single
/// object through the pipeline.
/// </summary>
[Parameter]
public SwitchParameter NoEnumerate { get; set; }
Comment thread
danstur marked this conversation as resolved.
Outdated

#endregion parameters

#region overrides
Expand Down Expand Up @@ -114,7 +120,7 @@ private bool ConvertFromJsonHelper(string input)
ThrowTerminatingError(error);
}

WriteObject(result);
WriteObject(result, !NoEnumerate.IsPresent);
return (result != null);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ Describe 'ConvertFrom-Json Unit Tests' -tags "CI" {
@{ AsHashtable = $true }
@{ AsHashtable = $false }
)
$testCasesWithAndWithoutNoEnumerateSwitch = @(
@{ NoEnumerate = $true }
@{ NoEnumerate = $false }
)
}

It 'Can convert a single-line object with AsHashtable switch set to <AsHashtable>' -TestCases $testCasesWithAndWithoutAsHashtableSwitch {
Expand Down Expand Up @@ -107,6 +111,27 @@ Describe 'ConvertFrom-Json Unit Tests' -tags "CI" {
Should -Throw -ErrorId "System.ArgumentException,Microsoft.PowerShell.Commands.ConvertFromJsonCommand"
}

It 'Can correctly round trip arrays with NoEnumerate switch set to <NoEnumerate>' -TestCases $testCasesWithAndWithoutNoEnumerateSwitch {
Param($NoEnumerate)
'[ 1, 2 ]' | ConvertFrom-Json -NoEnumerate:$NoEnumerate | ConvertTo-Json -Compress | Should -Be '[1,2]'
}

It 'Unravels array elements when NoEnumerate switch is not set' {
('[ 1, 2 ]' | ConvertFrom-Json | Measure-Object).Count | Should -Be 2
}

It 'Sends a Json array as a single element when NoEnumerate switch is set' {
('[ 1, 2 ]' | ConvertFrom-Json -NoEnumerate | Measure-Object).Count | Should -Be 1
}

It 'Cannot round trip single element arrays without NoEnumerate switch' {
'[ 1 ]' | ConvertFrom-Json | ConvertTo-Json | Should -Be 1
}

It 'Can round trip single element arrays with NoEnumerate switch' {
'[ 1 ]' | ConvertFrom-Json -NoEnumerate | ConvertTo-Json -Compress | Should -Be '[1]'
}

It 'Can convert null' {
'null' | ConvertFrom-Json | Should -Be $null
$out = '[1, null, 2]' | ConvertFrom-Json
Expand Down