首页 > 解决方案 > Powershell - convertTo-JSON 时添加“数据”块

问题描述

使用时如何添加"data" : [$var | convertTo-Json

的实际输出$var只是一个具有一些属性的对象,然后使用命令将其转换为 json convertTo-Json

这是我得到的:

[
    {
        "controllerID":  "0",
        "DiskID":  "0:1:0",
        "cName":  "PERCS130",

    },
    {
        "controllerID":  "0",
        "DiskID":  "0:1:1",
        "cName":  "PERCS130",
    }
]

但我需要这样的东西:

{
    "data": [
        {
            "controllerID":  "0",
            "DiskID":  "0:1:0",
            "cName":  "PERCS130",

        },
        {
            "controllerID":  "0",
            "DiskID":  "0:1:1",
            "cName":  "PERCS130",
        }
    ]
}

标签: powershell

解决方案


您显示的 JSON 由于逗号的 after 是无效的"cName": "PERCS130"。这可能是因为你在这里剥离了一些东西。

您需要做的是创建一个新的 json,其中一个新元素data包含当前 json 作为数组:

$json = @"
[
    {
        "controllerID":  "0",
        "DiskID":  "0:1:0",
        "cName":  "PERCS130"
    },

    {
        "controllerID":  "0",
        "DiskID":  "0:1:1",
        "cName":  "PERCS130"
    }
]
"@ | ConvertFrom-Json

$newjson = @{'data' = @($json)}
$newjson | ConvertTo-Json -Depth 3  # you may need to up the Depth value

结果:

{
    “数据”: [
                 {
                     “控制器ID”:“0”,
                     "磁盘ID": "0:1:0",
                     "cName": "PERCS130"
                 },
                 {
                     “控制器ID”:“0”,
                     "磁盘ID": "0:1:1",
                     "cName": "PERCS130"
                 }
             ]
}

PowerShell 不会产生“漂亮”的 json。如果您需要将其转换为适当间隔的 json,请参阅我的函数Format-Json


推荐阅读