Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse JSON from the Invoke-WebRequest in PowerShell?

When sending the GET request to the server, which uses self-signed certificate:

add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
        }
    }
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
$RESPONSE=Invoke-WebRequest -Uri https://yadayada:8080/bla -Method GET
echo $RESPONSE

I'm getting following Response:

StatusCode        : 200
StatusDescription : OK
Content           : {123, 10, 108, 111...}
RawContent        : HTTP/1.1 200 OK
                    Content-Length: 21
                    Date: Sat, 11 Jun 2016 10:11:03 GMT

                    {
                        flag:false
                    }
Headers           : {[Content-Length, 21], [Date, Sat, 11 Jun 2016 10:11:03 GMT]}
RawContentLength  : 21

Content contains some wired numbers, so I went after RawContent, how would I parse the JSON inside, ignoring headers? or is there a clean way to get Content from those numbers?

like image 593
user52028778 Avatar asked Jun 11 '16 10:06

user52028778


People also ask

How do I parse JSON data in PowerShell?

PowerShell makes it easy to modify JSON by converting JSON to a PSCustomObject. The object can then be modified easily like any other object. The object can then be exported back out using ConvertTo-Json. Now if we're on a computer without PowerShell 7.1 we try to run the same command in PowerShell 5.1 but it fails!

What is invoke-WebRequest in PowerShell?

The Invoke-WebRequest cmdlet sends HTTP and HTTPS requests to a web page or web service. It parses the response and returns collections of links, images, and other significant HTML elements. This cmdlet was introduced in PowerShell 3.0.


2 Answers

You could replace Invoke-WebRequest with Invoke-RestMethod which auto-converts json response to a psobject so you can use:

$response = Invoke-RestMethod -Uri "https://yadayada:8080/bla"
$response.flag 
like image 77
Frode F. Avatar answered Sep 30 '22 04:09

Frode F.


If you have a need to use Invoke-WebRequest over Invoke-RestMethod you can convert it to an object by turning it into a string first

$response = Invoke-WebRequest -Uri "https://yadayada:8080/bla"
$jsonObj = ConvertFrom-Json $([String]::new($response.Content))
like image 21
FictitiousWizard Avatar answered Sep 30 '22 04:09

FictitiousWizard