首页 > 解决方案 > 转换后Powershell缺少数组

问题描述

当我转换一个 powershell 对象时,属性bar和属性的数组foo丢失了。我使用以下命令将生成的 json 对象导出到文件:$stackoverflow| ConvertTo-Json | set-content '.\foobar.json'

@stackoverflow = @{
    name = "question"
    description = "stackoverflow is amazing!"
    version = 1.0
    myattribute = @(
        @{
            foo = @("value1")
            bar = @("value2")
        }
    )
}

我希望输出看起来像这样foo = ["value1"]and bar = ["value2],但 json 文件中的实际输出是foo = "value1"and bar = "value2"

谢谢您的帮助。

标签: arraysjsonpowershellobject

解决方案


通过引用版本号并从 myattribute 中删除 splat,我得到了它的预期工作:

$stackoverflow = @{
    name = "question"
    description = "stackoverflow is amazing!"
    version = "1.0"
    myattribute = (
        @{
            foo = @("value1")
            bar = @("value2")
        }
    )
}

从输出$stackoverflow | ConvertTo-Json

{
    "myattribute":  {
                        "bar":  [
                                    "value2"
                                ],
                        "foo":  [
                                    "value1"
                                ]
                    },
    "description":  "stackoverflow is amazing!",
    "name":  "question",
    "version":  "1.0"
}

推荐阅读