Kevin Pluck Kevin Pluck - 3 months ago 15
PowerShell Question

PowerShell's output of nested data types

I'm trying to create a nested data structure from some input and eventually convert it to JSON, but I am having trouble once it gets too deep.

The structure will be an array of a hash where one item is another array of a hash.

This sets up two arrays of a hash

$baz1
and
$baz2


PS D:\> $baz1 = @(@{foo="foo1"; bar="bar1"};@{foo="foo2";bar="bar2"};@{foo="foo3";bar="bar3"})
PS D:\> $baz2 = @(@{foo="foo1"; bar="bar1"};@{foo="foo2";bar="bar2"};@{foo="foo3";bar="bar3"})


As you can see, all above board:

PS D:\> $baz1

Name Value
---- -----
bar bar1
foo foo1
bar bar2
foo foo2
bar bar3
foo foo3


PS D:\> $baz1|ConvertTo-Json
[
{
"bar": "bar1",
"foo": "foo1"
},
{
"bar": "bar2",
"foo": "foo2"
},
{
"bar": "bar3",
"foo": "foo3"
}
]
PS D:\>


But when I add the array to
$fuz
it all goes pear-shaped:

PS D:\> $fuz = @(@{foo="bar"; bash=$baz1};@{foo="beep";bash=$baz2})
PS D:\> $fuz

Name Value
---- -----
foo bar
bash {System.Collections.Hashtable, System.Collections.Hashtable, System.Collections.Hashtable}
foo beep
bash {System.Collections.Hashtable, System.Collections.Hashtable, System.Collections.Hashtable}


PS D:\> $fuz|ConvertTo-Json
[
{
"foo": "bar",
"bash": [
"System.Collections.Hashtable",
"System.Collections.Hashtable",
"System.Collections.Hashtable"
]
},
{
"foo": "beep",
"bash": [
"System.Collections.Hashtable",
"System.Collections.Hashtable",
"System.Collections.Hashtable"
]
}
]


Even without the
$baz1
step

PS D:\> @(@{foo="bar"; bash=@(@{foo="foo1"; bar="bar1"};@{foo="foo2";bar="bar2"};@{foo="foo3";bar="bar3"})};@{foo="beep";bash=$baz2})

Name Value
---- -----
foo bar
bash {System.Collections.Hashtable, System.Collections.Hashtable, System.Collections.Hashtable}
foo beep
bash {System.Collections.Hashtable, System.Collections.Hashtable, System.Collections.Hashtable}


PS D:\>


Really appreciate some help here!

Answer

Use the -Depth parameter on the ConvertTo-Json cmdlet to expand the child property values.

Comments