问题描述
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[]}}
能够通过访问 $inputjson.clients[0].id
来查看 id 值,但是在 id=System.Object[]
中使用 $inputjson
的有效负载时,API 无法识别它。我正在使用 Invoke-RestMethod
将负载发布到 API。
知道如何解析负载中的 id=System.Object[]
,以便 API 正确识别它吗?
顺便说一句,API 使用 cURL cmd 识别相同的输入 json(原样)。
解决方法
您可以像这样发布纯 JSON,而不是使用 ConvertFrom-Json
cmdlet 将 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 版本,在从 JSON 转换或转换为 JSON 时,您可能需要使用 -Depth
参数。