【问题标题】:Loop json object using for loop or while loop in Powershell在Powershell中使用for循环或while循环循环json对象
【发布时间】:2021-05-21 16:31:01
【问题描述】:

由于我是 Powershell 的新手,有人可以支持循环部分吗? 下面是 Test.json 文件中的 json 格式:

{
    "Pre-Production_AFM": {
        "allowedapps": ["app1", "app2"]
    },
    "Production_AFM": {
        "allowedapps": ["app1", "app2"]
    }
}

我正在读取下面的json文件

$json = (Get-Content "Test.json" -Raw) | ConvertFrom-Json

我需要循环并动态获取第一个和第二个对象 - “Pre-Production_AFM”和“Production_AFM”。

现在我已经编写了如下代码:

foreach($i in $json){

        if($i -contains "AFM"){
       Write host "execute some code"
     }
}

我的问题是 - $i 会动态持有对象“Pre-Production_AFM”吗? 如果不是,请提出动态获取对象以供进一步执行的方法。

【问题讨论】:

    标签: json powershell


    【解决方案1】:
    # read the json text
    $json = @"
    {
        "Pre-Production_AFM": {
            "allowedapps": ["app1", "app2"]
        },
        "Production_AFM": {
            "allowedapps": ["app1", "app2"]
        }
    }
    "@
    
    # convert to a PSCustomObject
    $data = $json | ConvertFrom-Json
    
    # just to prove it's a PSCustomObject...
    $data.GetType().FullName
    # System.Management.Automation.PSCustomObject
    
    # now we can filter the properties by name like this:
    $afmProperties = $data.psobject.Properties | where-object { $_.Name -like "*_AFM" };
    
    # and loop through all the "*_AFM" properties
    foreach( $afmProperty in $afmProperties )
    {
       $allowedApps = $afmProperty.Value.allowedApps
       # do stuff
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-21
      • 2014-08-21
      • 2013-07-21
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      • 2013-06-12
      • 2019-11-10
      相关资源
      最近更新 更多