0

I'm trying to pack my data into objects before displaying them with ConvertTo-Json. The test case below shows perfectly how I'm dealing with data and what problem occurs:

$array = @("a","b","c")
$data = @{"sub" = @{"sub-sub" = $array}}
$output = @{"root" = $data}
ConvertTo-Json -InputObject $data
ConvertTo-Json -InputObject $output

Output (formatted by hand for clarity):

          { "sub": { "sub-sub": [ "a", "b", "c" ] }}
{ "root": { "sub": { "sub-sub": "a b c" } }}

Is there any way to assign $data to $output without this weird implicit casting?

5
  • 2
    ConvertTo-Json -InputObject $output -Depth 3 Commented Apr 10, 2016 at 8:29
  • Thank you! ...although -Depth 1 gives System.Collections.Hashtable for "sub-sub" but -Depth 2 gives "a b c" for ["a","b","c"] instead of Object[] and I think this is very illogical Commented Apr 10, 2016 at 8:39
  • 1
    Depth is simply the number of nested levels at which PowerShell will "unravel" a value. Otherwise, it'll default to the objects string representation, which is exactly what yo see Commented Apr 10, 2016 at 8:41
  • And by string representation you mean "[string]" and not "... | Out-String". Now it's clear. Commented Apr 10, 2016 at 8:57
  • Correct, the object itself is cast to a string Commented Apr 10, 2016 at 8:58

1 Answer 1

5

As mentioned in the comments, ConvertTo-Json will try to flatten the object structure beyond a maximum nesting level, or depth, by converting whatever object it finds beyond that depth to a string.

The default depth is 2, but you can specify that it should go deeper with the Depth parameter:

PS C:\> @{root=@{level1=@{level2=@("level3-1","level3-2")}}}|ConvertTo-Json
{
    "root":  {
        "level1":  {
            "level2":  "level3-1 level3-2"
        }
    }
}
PS C:\> @{root=@{level1=@{level2=@("level3-1","level3-2")}}}|ConvertTo-Json -Depth 3
{
    "root":  {
        "level1":  {
            "level2":  [
                "level3-1",
                "level3-2"
            ]
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.