首页 > 解决方案 > Invoke-RestMethod 未正确传递有效负载中的 System.Object[] 字段

问题描述

json 有效负载如下所示:

{
  "clients": [
    {
      "scope": "scope1",
      "claim": "scope1",
      "id": ["123", "567"]
    },
    {
      "scope": "scope2",
      "claim": "claim2",
      "id": ["321", "765"]
    }
  ]
}
> $inputjson = (((get-content .\inputfile.json) -Join " " ) | convertfrom-json )

> echo $inputjson

 clients                                                                               
 -------                                                                 
 {@{scope=scope1; claim=scope1; id=System.Object[]}, @{scope=scope2; claim=claim2; id=System.Object[]}}

能够通过访问来查看id$inputjson.clients[0].id,但是使用 in 的这个有效负载id=System.Object[]$inputjsonAPI 无法识别它。我正在使用Invoke-RestMethod将有效负载发布到 API。

知道如何解析id=System.Object[]有效负载中的内容,以便 API 正确识别它吗?

顺便说一句,API 使用 cURL cmd 识别相同的输入 json(原样)。

标签: powershellpowershell-2.0powershell-3.0azure-powershell

解决方案


您可以像这样发布纯 JSON,而不是使用ConvertFrom-Jsoncmdlet 将 JSON 转换为 .NET 对象并发布 .NET 对象:

$myJson = @"
{
  "clients": [
    {
      "scope": "scope1",
      "claim": "scope1",
      "id": ["123", "567"]
    },
    {
      "scope": "scope2",
      "claim": "claim2",
      "id": ["321", "765"]
    }
  ]
}
"@
Invoke-RestMethod -Uri "" -Method Post -Body $myJson -ContentType "application/json"

如果您想处理从文件中读取的 JSON,在发布之前,您可以像以前一样转换它并将其转换回纯 JSON。根据您的 PowerShell 版本,-Depth在从 JSON 转换为 JSON 时,您可能需要使用该参数。


推荐阅读