将json变量分解为数组中的各个项

时间:2015-07-14 00:04:03

标签: arrays json powershell-v2.0

如何将以下json变量分解为数组中的各个项?

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

例如,上述内容将转换为数组,包含以下内容:

数组项目0

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

数组项目1

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

数组项目2

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

我想在Powershell 2.0中完成此操作并单独访问每个。到目前为止,这是我设法完成的任务:

$jsonarr = @()
$arr = (Get-Content C:\json.json| Out-String).replace("[","") -split "(})," -replace "]",""
$jsonarr += $arr[0..1] -join ""
$jsonarr += $arr[2..3] -join ""
$jsonarr += $arr[4]

然而,这是非常不灵活的,并且只要我有另一台服务器的详细信息到JSON文件就会停止工作。

1 个答案:

答案 0 :(得分:1)

对于PowerShell v2,您可以使用Convert between PowerShell and JSON

PS

PowerShell v3 +,使用上面的工具应该是相同的:

$json = '[  
   {  
      "server":{  
         "name":"myUbuntuServer1",
         "imageRef":"3afe97b2-26dc-49c5-a2cc-a2fc8d80c001",
         "flavorRef":"6"
      }
   },
   {  
      "server":{  
         "name":"myUbuntuServer2",
         "imageRef":"3afe97b2-26dc-49c5-a2cc-a2fc8d80c001",
         "flavorRef":"6"
      }
   },
   {  
      "server":{  
         "name":"myUbuntuServer3",
         "imageRef":"3afe97b2-26dc-49c5-a2cc-a2fc8d80c001",
         "flavorRef":"6"
      }
   }
]'

$servers = ConvertFrom-Json $json

$servers.server.imageRef

返回

3afe97b2-26dc-49c5-a2cc-a2fc8d80c001
3afe97b2-26dc-49c5-a2cc-a2fc8d80c001
3afe97b2-26dc-49c5-a2cc-a2fc8d80c001

另外,不要忘记“Get-Member”

PPS

PS C:\Users\joshua\Desktop> $servers.server| where name -EQ myUbuntuServer2 

name            imageRef                             flavorRef
----            --------                             ---------
myUbuntuServer2 3afe97b2-26dc-49c5-a2cc-a2fc8d80c001 6        



PS C:\Users\joshua\Desktop> $servers.server| where name -EQ myUbuntuServer2 | select -Property flavorRef

flavorRef
---------
6

PPPS

也是当然

$servers.server[0]

你应该能够按姓名索引,但我正在制作一些愚蠢的错误atm