[英]How to parse JSON from the Invoke-WebRequest in PowerShell?
When sending the GET request to the server, which uses self-signed certificate:向使用自签名证书的服务器发送 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
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?内容包含一些有线数字,所以我去了 RawContent,我将如何解析里面的 JSON,忽略标头? or is there a clean way to get Content from those numbers?
或者有没有一种干净的方法可以从这些数字中获取内容?
You could replace Invoke-WebRequest
with Invoke-RestMethod
which auto-converts json response to a psobject
so you can use:您可以将
Invoke-WebRequest
替换为Invoke-RestMethod
,后者将 json 响应自动转换为psobject
以便您可以使用:
$response = Invoke-RestMethod -Uri "https://yadayada:8080/bla"
$response.flag
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如果您需要在
Invoke-RestMethod
上使用Invoke-WebRequest
,您可以通过先将其转换为字符串来将其转换为对象
$response = Invoke-WebRequest -Uri "https://yadayada:8080/bla"
$jsonObj = ConvertFrom-Json $([String]::new($response.Content))
This way:这样:
$response = Invoke-WebRequest -Uri <your_uri>
if ($response.statuscode -eq '200') {
$keyValue= ConvertFrom-Json $response.Content | Select-Object -expand "<your_key_name>"
}
If you have a wrapper than include the name in the path.如果您有一个包装器,则在路径中包含名称。
$response=Invoke-RestMethod -Method GET -ContentType "application/json" -Headers $headers -Uri $Url
foreach($element in $response.baskets.fixed_asset_rents)
{
Write-Host $element
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.