2016-10-04 27 views
0

遞歸循環,我有我的JSON如下通過JSON對象在PowerShell中

{ 
    "cluster": [ 
    { 
     "id": "cluster1.1", 
     "color": "blue", 
     "segment": [ 
     { 
      "id": "segment1.1", 
      "color": "green" 
     } 
     ] 
    }, 
    { 
     "id": "cluster1.2", 
     "color": [ 
     "blue", 
     "red" 
     ], 
     "segment": [ 
     { 
      "id": "segment1.2", 
      "color": "Yellow" 
     } 
     ] 
    }, 
    { 
     "id": "cluster1.3", 
     "color": "Orange", 
     "segment": [ 
     { 
      "id": "cluster1.3", 
      "color": "black" 
     }, 
     { 
      "id": "cluster1.4", 
      "color": "Green" 
     }, 
     { 
      "id": "cluster1.5", 
      "color": "red" 
     } 
     ] 
    }, 
    { 
     "id": "cluster1.4", 
     "color": [ 
     "blue", 
     "red" 
     ], 
     "segment": [ 
     { 
      "id": "cluster1.4", 
      "color": "red" 
     }, 
     { 
      "id": "cluster1.5", 
      "color": "blue" 
     }, 
     { 
      "id": "cluster1.6", 
      "color": "Yellow" 
     } 
     ] 
    } 
    ] 
} 

我想循環這個遞歸遍歷所有的節點,我得到的內容與下面的代碼如下,但我沒有得到通過所有節點

$jsonData = (Get-Content -FilePath) -join "`n" | ConvertFrom-Json 

for($i=0; $i -lt $jsonData.cluster.Length; $i++) 
{ 
    $clusterInfo= $ReportingPackage.cluster[$i] 
    $clusterInfo.Color 
} 

我需要通過所有段遞歸找到一種方式來循環和顏色

回答

1

Array.ElementProperty簡寫形式僅爲數組的直接元素提取屬性。 手動枚舉所述子元素的屬性:

ForEach ($cluster in $jsonData.cluster) { 
    $cluster.color 
    $cluster.segment.color 
} 

您可能需要使用一個健全性檢查:if ($cluster.segment) { $cluster.segment.color }

收集所有的顏色陣列中的最簡單的方法是配管:

$allColors = $jsonData.cluster | ForEach { 
    $_.color 
    $_.segment.color 
} 
+0

嗨,謝謝當我試圖獲得獨特的顏色與出來重複我不能得到'$ allColors.color |選擇-Unique'你能幫我嗎 – Nithya

+0

1.這是一個不同的問題。 2.確保始終在PowerShell ISE或控制檯中檢查數據的內容,因爲我的第二個示例生成一個不帶'.color'屬性的普通字符串數組:'$ allColors |選擇-unique' – wOxxOm