【问题标题】:Looping through Json object recursively in powershell在powershell中递归循环遍历Json对象
【发布时间】:2016-10-04 18:05:14
【问题描述】:

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

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

【问题讨论】:

    标签: powershell-4.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
    }
    

    【讨论】:

    • 嗨谢谢当我试图获得独特的颜色而不复制我无法获得$allColors.color| select -Unique你能帮我吗
    • 1.这是一个不同的问题。 2. 确保始终在 PowerShell ISE 或控制台中检查数据的内容,因为我的第二个示例生成了一个没有 .color 属性的纯字符串数组:$allColors | select -unique
    猜你喜欢
    • 1970-01-01
    • 2011-04-18
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    相关资源
    最近更新 更多