简体   繁体   English

如何解析/访问 Powershell 4 中 Invoke-WebRequest 返回的 JSON

[英]How to parse/access JSON returned by Invoke-WebRequest in Powershell 4

I have the following call to an API in a powershell script (Powershell 4.0):我在 powershell 脚本(Powershell 4.0)中对 API 进行了以下调用:

$Json = Invoke-WebRequest -Uri $RequestURL -UseBasicParsing -Headers $headers -ContentType  'application/json; charset=utf-8' -Method POST -Body $postParams -TimeoutSec 40 

...and the content of the response (which is a string in JSON format) is written to a file: ...并将响应的内容(JSON 格式的字符串)写入文件:

Set-Content $path -Value $Json.Content

An example of a typical response...典型响应的示例...

{
    "MyArray": [{
        "MyField": "A1",
        "MyField2": "A2"
    }, {
        "MyField": "B1",
        "MyField2": "B2"
    }]
}

All well and good, but now I have a requirement to parse the returned content as JSON and query some properties from within this Powershell script.一切都很好,但现在我需要将返回的内容解析为 JSON 并从这个 Powershell 脚本中查询一些属性。

I presume I need to convert my string to 'proper' JSON and then to a powershell object in order to access the properties...so I have tried combinations of ConvertTo-Json and ConvertFrom-Json but can't ever seem to access it in anything other than a string.我想我需要将我的字符串转换为“正确的”JSON,然后转换为 powershell 对象才能访问属性......所以我尝试了 ConvertTo-Json 和 ConvertFrom-Json 的组合,但似乎永远无法访问它在字符串以外的任何东西中。 For example...例如...

    $x = $Json.Content | ConvertTo-Json
    Write-Host $x.MyArray[0].MyField

    $y = $x | ConvertFrom-Json
    Write-Host $y[0].MyArray[0].MyField

In both cases above I get an error "Cannot index into a null array" suggesting that MyArray is null.在上述两种情况下,我都收到错误“无法索引到空数组”,表明 MyArray 为空。

How do I convert my $Json response object into an object I can drill down into?如何将我的 $Json 响应对象转换为我可以深入研究的对象?

See ConvertFrom-Json请参阅ConvertFrom-Json

Converts a JSON-formatted string to a custom object or a hash table.将 JSON 格式的字符串转换为自定义对象或哈希表。

The ConvertFrom-Json cmdlet converts a JavaScript Object Notation (JSON) formatted string to a custom PSCustomObject object that has a property for each field in the JSON string. ConvertFrom-Json cmdlet 将 JavaScript 对象表示法 (JSON) 格式的字符串转换为自定义 PSCustomObject 对象,该对象具有 JSON 字符串中每个字段的属性。

Once you get the response converted to custom object or a hash table, you can access the individual properties一旦您将响应转换为自定义对象或哈希表,您就可以访问各个属性

The link includes coding examples该链接包括编码示例

This seems to work...这似乎有效...

[void][System.Reflection.Assembly]::LoadWithPartialName("System.Web.Extensions")
    $x = (New-Object -TypeName System.Web.Script.Serialization.JavaScriptSerializer -Property @{MaxJsonLength=67108864}).DeserializeObject($Json.Content)
    Write-Host $x.MyArray[0].MyField

...although not sure why yet. ...虽然不知道为什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM