使用Get-Content并将json文件拆分为3个部分

时间:2015-07-13 23:07:28

标签: arrays json powershell-v2.0

如果我有以下格式的json文件:

{
    "server" : {
        "name" : "myUbuntuServer1",
        "imageRef" : "3afe97b2-26dc-49c5-a2cc-a2fc8d80c001",
        "flavorRef" : "9" }
}
{
    "server" : {
        "name" : "myUbuntuServer2",
        "imageRef" : "3afe97b2-26dc-49c5-a2cc-a2fc8d80c001",
        "flavorRef" : "6" }
}
{
    "server" : {
        "name" : "myUbuntuServer3",
        "imageRef" : "3afe97b2-26dc-49c5-a2cc-a2fc8d80c001",
        "flavorRef" : "3" }
}

如何根据文件中检测到的服务器数量将其拆分并将每个块分配为数组项,即

数组项目0

{
    "server" : {
        "name" : "myUbuntuServer1",
        "imageRef" : "3afe97b2-26dc-49c5-a2cc-a2fc8d80c001",
        "flavorRef" : "9" }
}

数组项目1

{
    "server" : {
        "name" : "myUbuntuServer2",
        "imageRef" : "3afe97b2-26dc-49c5-a2cc-a2fc8d80c001",
        "flavorRef" : "6" }
}

数组第2项

{
    "server" : {
        "name" : "myUbuntuServer3",
        "imageRef" : "3afe97b2-26dc-49c5-a2cc-a2fc8d80c001",
        "flavorRef" : "3" }
}

到目前为止,这是我的代码:

$file = "servers.json"
$request = Get-Content $file
createServer $request

我想根据服务器将文件拆分成段,然后将$request赋值和createServer函数包装在for循环中,并传递数组中的每个项目。

所以它看起来像:

$file = "servers.json"
$request = Get-Content $file

#split file up into three here and assign to an array

foreach ($request in $array) {
    createServer $request
}

我将如何在Powershell v2中完成此任务?

1 个答案:

答案 0 :(得分:1)

JSON格式错误,这是一种有效的格式:

{
    "servers": [
        {
            "name": "myUbuntuServer1",
            "imageRef": "3afe97b2-26dc-49c5-a2cc-a2fc8d80c001",
            "flavorRef": "9"
        },
        {
            "name": "myUbuntuServer1",
            "imageRef": "3afe97b2-26dc-49c5-a2cc-a2fc8d80c001",
            "flavorRef": "9"
        },
        {
            "name": "myUbuntuServer1",
            "imageRef": "3afe97b2-26dc-49c5-a2cc-a2fc8d80c001",
            "flavorRef": "9"
        }
    ]
}

您可以在服务器键内迭代它已经是一个数组。 希望你能帮忙。