在powershell中递归遍历Json对象

时间:2016-10-04 05:58:28

标签: powershell-v4.0

我的json如下

{
  "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 个答案:

答案 0 :(得分: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
}