小编典典

如何在PowerShell中从Invoke-WebRequest解析JSON?

json

将GET请求发送到使用自签名证书的服务器时:

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

我得到以下回应:

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

内容包含一些有线号码,因此我追随RawContent,该如何解析内部的JSON,而忽略标题?还是有一种干净的方法来从这些数字中获取内容?


阅读 530

收藏
2020-07-27

共1个答案

小编典典

你可以替换Invoke-WebRequest使用Invoke-RestMethod其自动转换JSON响应psobject,以便您可以使用:

$response = Invoke-RestMethod -Uri "https://yadayada:8080/bla"
$response.flag
2020-07-27