vin_Bin87
vin_Bin87

Reputation: 348

Powershell Invoke-WebRequest returns array of objects but processes as if there is only 1

$path = "https://api.statuspage.io/v1/pages/$page_id/$endpoint"
$req  = Invoke-WebRequest -Uri $path -Method GET

This request returns an array of objects (50+). I can see this by running a Write-Host $req

Problem is, when I try something like

foreach($i in $req) {
  Write-Host $i
}

I am given the entire object. And similarly, if I run Write-Host $req.length I am given 1. What gives?

Additionally, there is no way to run something like

$global:res = ConvertFrom-Json $req

Because it's already being returned as a JSON

Upvotes: 2

Views: 4185

Answers (1)

mklement0
mklement0

Reputation: 438073

If your intent is to parse the JSON text into (nested) objects ([pscustomobject] graphs) anyway, you can simply use Invoke-RestMethod rather than Invoke-WebRequest, because Invoke-RestMethod has ConvertFrom-Json built in, in a manner of speaking:

$path = "https://api.statuspage.io/v1/pages/$page_id/$endpoint"

# Retrieves JSON *and* parses it into objects.
$result = Invoke-RestMethod -Uri $path -Method GET

As for what you tried:

$req = Invoke-WebRequest ...

Invoke-WebRequest returns a single object, namely and instance of BasicHtmlWebResponseObject (PowerShell [Core] v6+) / HtmlWebResponseObject (Windows PowerShell), which is a wrapper object with metadata that stores the content of the response received in the .Content property.

In your case, .Content contains JSON as a single string, which ConvertFrom-Json can parse into a nested object(s).

To parse this JSON string into one or more (potentially nested) objects ([pscustomobject] graphs):

$result = ConvertFrom-Json $req.Content

Note that even $result = ConvertFrom-Json $req would work, because when a response object is implicitly stringified, it interpolates to the value of its .Content property.

As Theo points out in a comment, you can also use the pipeline:

$result = $req | ConvertFrom-Json

Upvotes: 2

Related Questions