【问题标题】:How to parse JSON from the Invoke-WebRequest in PowerShell?如何从 PowerShell 中的 Invoke-WebRequest 解析 JSON?
【发布时间】:2021-11-07 22:55:31
【问题描述】:

向使用自签名证书的服务器发送 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

Content 包含一些有线数字,所以我追求 RawContent,我将如何解析里面的 JSON,忽略标题?还是有一种干净的方法可以从这些数字中获取内容?

【问题讨论】:

  • 您需要 JSON 还是只需要这些值?您可以将Invoke-WebRequest 替换为Invoke-RestMethod,它会自动将json 响应转换为psobject,这样您就可以使用$response = Intoke-RestMethod -Uri "https://yadayada:8080/bla"; $response.flag
  • 感谢 Frode F.,这解决了我的难题。对我来说,JSON 值已经足够好了,如果您将此作为答案重新发布,我会接受它

标签: json powershell response


【解决方案1】:

您可以将Invoke-WebRequest 替换为Invoke-RestMethod,它会自动将json 响应转换为psobject,以便您可以使用:

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

【讨论】:

    【解决方案2】:

    如果您需要使用Invoke-WebRequest 而不是Invoke-RestMethod,您可以先将其转换为字符串,然后将其转换为对象

    $response = Invoke-WebRequest -Uri "https://yadayada:8080/bla"
    $jsonObj = ConvertFrom-Json $([String]::new($response.Content))
    

    【讨论】:

    • 请注意,以防它对其他人有所帮助-此答案中第 2 行的语法不适用于 Powershell v4-但 Invoke-RestMethod 确实有效。 Invoke-RestMethod 也有一个好处(至少在 Powershell v4 中)不依赖于 IE - 要让 Invoke-WebRequest 在没有可用 IE 的环境中工作,我必须提供 -UseBasicParsing。
    【解决方案3】:

    这边:

    $response = Invoke-WebRequest -Uri <your_uri>
    if ($response.statuscode -eq '200') {
        $keyValue= ConvertFrom-Json $response.Content | Select-Object -expand "<your_key_name>"
    }
    

    【讨论】:

    • 谢谢,这是嵌套 json 的正确答案
    【解决方案4】:

    如果你有一个包装器而不是在路径中包含名称。

      $response=Invoke-RestMethod -Method GET -ContentType "application/json" -Headers $headers -Uri $Url
    
      foreach($element in $response.baskets.fixed_asset_rents)
      {
            Write-Host $element
      }
    

    【讨论】:

      猜你喜欢
      • 2020-05-06
      • 2017-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-19
      • 2020-03-17
      相关资源
      最近更新 更多