0

I have my json as follows

{
  "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"
        }
      ]
    }
  ]
}

I would like to loop this recursively through all nodes, I am getting the content as follows with the following code but I am not getting through all the nodes

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

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

I need to recursively find a way to loop through all segments and colors

wOxxOm
  • 65,848
  • 11
  • 132
  • 136
Nithya
  • 47
  • 2
  • 14

1 Answers1

1

Array.ElementProperty shorthand fetches the properties only for the immediate elements of the array. Enumerate the sub-elements' properties manually:

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

You may want to use a sanity check: if ($cluster.segment) { $cluster.segment.color }

To collect all colors in an array the simplest method is piping:

$allColors = $jsonData.cluster | ForEach {
    $_.color
    $_.segment.color
}
wOxxOm
  • 65,848
  • 11
  • 132
  • 136
  • Hi thanks When I am trying to get the unique colors with out duplicating I am not able to get `$allColors.color| select -Unique` can you help me – Nithya Oct 04 '16 at 10:15
  • 1
    1. This is a different question. 2. Make sure to always inspect the contents of your data in PowerShell ISE or console because my second example produces an array of plain strings without `.color` property: `$allColors | select -unique` – wOxxOm Oct 04 '16 at 10:18