Bryan Arreola
Bryan Arreola

Reputation: 307

Iterate over a JSON response from API in Powershell

It's kinda tricky because the API response is supposed to be in JSON format, however, if I try to access a property it returns null

PS C:\Users\bryanar> $response.ClientASN


Then I checked the type of the response

PS C:\Users\bryanar> $response.GetType()

IsPublic IsSerial Name                                     BaseType                                                                                                                                                                                              
-------- -------- ----                                     --------                                                                                                                                                                                              
True     True     String                                   System.Object 

If I try to approach to the object in a different way I even get the error that's supposed to mean that the variable is not a JSON object

At line:1 char:20
+ $response| ConvertFrom-Json | Select ClientASN
+                    ~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [ConvertFrom-Json], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.ConvertFromJsonCommand

So I tell PowerShell to do so but even then I get a null value

$response= Invoke-RestMethod `
    -Uri "https://api.cloudflare.com/client/v4/zones/$zoneID/logs/received?start=$startDate&end=$endDate&fields=$fields" `
    -Method GET `
    -Headers $header `
    -ContentType 'application/json; charset=utf-8' | ConvertTo-Json

PS C:\Users\bryanar> $response| ConvertFrom-Json | Select ClientASN

ClientASN
---------
      

This is what $response shows when I print it in the console

{"ClientASN": 8075,"ClientCountry": "us","ClientIP": "0.0.0.0"}
{"ClientASN": 7545,"ClientCountry": "au","ClientIP": "0.0.0.0"}
{"ClientASN": 8075,"ClientCountry": "us","ClientIP": "0.0.0.0"}
{"ClientASN": 7545,"ClientCountry": "au","ClientIP": "0.0.0.0"}

Upvotes: 0

Views: 210

Answers (1)

Drew
Drew

Reputation: 4030

Adding some Parentheses works, not sure why. Something to do with processing the data before sending it to the Select pipe. Those more knowledgeable should be able to explain the very specific reason.

$JSON = @'
[{
        "ClientASN": 8075,
        "ClientCountry": "us",
        "ClientIP": "0.0.0.0"
    },
    {
        "ClientASN": 8075,
        "ClientCountry": "us",
        "ClientIP": "0.0.0.0"
    },
    {
        "ClientASN": 8075,
        "ClientCountry": "us",
        "ClientIP": "0.0.0.0"
    },
    {
        "ClientASN": 7545,
        "ClientCountry": "au",
        "ClientIP": "0.0.0.0"
    }
]
'@

($JSON | ConvertFrom-Json) | select ClientASN

Upvotes: 1

Related Questions