phydeauxman
phydeauxman

Reputation: 1720

Need help parsing JSON with PowerShell

I have the JSON block below that I am trying to parse with PowerShell. What the JSON is for is to denote permissions that an AD group should be given on an Azure App Registration. An application will have multiple groups assigned to it and each group will have a unique set of roles (permissions). The full JSON file has several of these application blocks.

Basically, what I want to be able to do with PowerShell is to take the application, query Azure AD to get the application resource and then modify the resource to assign each group to the app with its roles using New-AzureADGroupAppRoleAssignment.

Conventional thinking would be the I need a loop nested inside of a loop nested inside of a loop where the first loop grabs the application block, then the second loop grabs the groupname block and then the third loop grabs the array of roles for that group.

 "application": 
  [
    {
      "groupname": "adgroup1",
      "roles": [ 
        "Permission1",
        "Permission2",
        "Permission3",
        "Permission4",
        "Permission5",    
        "Permission6" 
      ]
    },
    {
      "groupname": "adgroup2",
      "roles": [ 
        "Permission1",
        "Permission2",
        "Permission4",
        "Permission5",    
        "Permission6" 
      ]
    }

Upvotes: 1

Views: 476

Answers (2)

No Refunds No Returns
No Refunds No Returns

Reputation: 8356

Something like this should get you started

$json = SomethingThatGetsJson | ConvertFrom-Json
$json.application | % {
   $data = $_
   Write-Host $data.groupname
   $data.roles | % {
      $role = $_
      Write-Host $role
   }
}

% is shorthand for ForEach-Object if you want to get some more details on that. $_ is the element value in the current iteration of the enumeration.

Upvotes: 1

Nick
Nick

Reputation: 1863

So long as the JSON returned is valid you should use the ConvertFrom-Json cmdlet, It will convert the JSON string in to a proper object you can dot walk through and run your other standard cmdlets against like select, where, foreach etc

Upvotes: 0

Related Questions