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

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

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
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.