Search code examples
powershellinvoke-webrequest

Iterating through Invoke-WebRequest JSON result


I am trying to iterate the result of a webrequest call through powershell

$response = Invoke-WebRequest -URI $apiUri -Method Get -UseBasicParsing
$response

Result:

StatusCode        : 200
StatusDescription : OK
Content           : {"tenants":[{"name":"default","active":true},{"name":"tenant1","active":true}]}
RawContent        : HTTP/1.1 200 OK
...

Using ConvertFromJson

$parsed = $response.Content | ConvertFrom-Json
$parsed

Result:

tenants : {@{name=default; active=True}, @{name=tenant1; active=True}}

Now, I want to list all the "name" value like this

Name
--------
default
tenant1

I've tried iterating it using this script but can't get the result:

$parsed | Select-Object -Property name | ForEach-Object {
    Write-Host $_.name
}

Solution

  • The code below will output a table of names:

    $json = '{"tenants":[{"name":"default","active":true},{"name":"tenant1","active":true}]}'
    
    $data = $json | ConvertFrom-Json
    
    $data.tenants | ft name
    
    #name
    #----
    #default
    #tenant1
    

    If you want to capture them into a variable as an array you can use a feature called Member Enumeration:

    $names = $data.tenants.name;
    
    $names
    #default
    #tenant1