Unexpected array to string conversion

只愿长相守 提交于 2019-12-17 21:23:49

问题


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?


回答1:


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"
            ]
        }
    }
}


来源:https://stackoverflow.com/questions/36526972/unexpected-array-to-string-conversion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!