意外的数组到字符串转换 [英] Unexpected array to string conversion

查看:38
本文介绍了意外的数组到字符串转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 ConvertTo-Json 显示它们之前,我试图将数据打包到对象中.下面的测试用例完美地展示了我如何处理数据以及发生了什么问题:

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

有没有什么方法可以将 $data 分配给 $output 而没有这种奇怪的隐式转换?

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

推荐答案

正如评论中提到的,ConvertTo-Json 将尝试将对象结构扁平化 超出最大值嵌套级别或深度,通过将它找到的超出该深度的任何对象转换为字符串.

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.

默认深度为 2,但您可以使用 Depth 参数指定它应该更深:

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

这篇关于意外的数组到字符串转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆