在 powershell 中递归遍历 Json 对象

Looping through Json object recursively in powershell

我的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
}

我需要递归地找到一种遍历所有段和颜色的方法

Array.ElementProperty shorthand 仅为数组的直接元素获取属性。 手动枚举子元素的属性:

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

您可能想要使用完整性检查:if ($cluster.segment) { $cluster.segment.color }

要将所有颜色收集到一个数组中,最简单的方法是管道:

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