json - Powershell - 大括号内大括号的 JSON 语法
问题描述
Powershell 5.1 - 我正在使用数据Invoke-RestMethod
到POST
端点。
API 调用的主体在 JSON 中如下所示:
{
"ServiceKind": "Custom",
"ApplicationName": "TestApp",
"ServiceName": "TestService",
"ServiceTypeName": "TestServiceType",
"PartitionDescription": {
"PartitionScheme": "Singleton"
},
"InstanceCount": "1"
}
我无法在 Powershell 中正确获取语法,它似乎与 PartitionDescription 键有关。
这是我所拥有的,它在运行时继续抛出错误:
$ServiceKind = 'Custom'
$ApplicationName = 'TestApp'
$ServiceName = 'TestService'
$ServiceTypeName = 'TestServiceType'
$PartitionDescription = "{PartitionScheme = 'Singleton'}"
$InstanceCount = '1'
$url = 'https://www.contoso.com'
$headers = 'our headers'
$bodyTest = @{
ServiceKind = $ServiceKind
ApplicationName = $ApplicationName
ServiceName = $ServiceName
ServiceTypeName = $ServiceTypeName
PartitionDescription = $PartitionDescription
}
Invoke-RestMethod -Uri $url -Headers $headers -body $body -Method Post -ContentType ‘application/json’
错误信息:
Invoke-RestMethod : {"Error":{"Code":"E_INVALIDARG","Message":"The request body can't be deserialized. Make sure it contains a valid PartitionedServiceDescWrapper object."}}
我确定它与$PartitionDescription
值有关,但我无法让任何语法正常工作。如果我在没有参数的情况下传递 API 调用,$body
我不会收到任何错误。
解决方案
您没有正确嵌套对象:
$body = @{
ServiceKind = 'Custom'
ApplicationName = 'TestApp'
ServiceName = 'TestService'
ServiceTypeName = 'TestServiceType'
PartitionDescription = @{
PartitionScheme = 'Singleton'
}
InstanceCount = '1'
} | ConvertTo-Json
为了进一步改善这一点:
$irmParams = @{
Uri = 'https://www.contoso.com'
Method = 'POST'
ContentType = 'application/json'
Headers = @{ Key = 'Value' }
Body = @{
ServiceKind = 'Custom'
ApplicationName = 'TestApp'
ServiceName = 'TestService'
ServiceTypeName = 'TestServiceType'
PartitionDescription = @{
PartitionScheme = 'Singleton'
}
InstanceCount = '1'
} | ConvertTo-Json
}
Invoke-RestMethod @irmParams
推荐阅读
- java - DefaultOidcUser 不能转换为类 CustomOAuth2User
- javascript - TypeError:无法读取属性 React JS
- kotlin - 如何在 Kotlin 中等待 billingClient.startConnection
- cognos - 如何在 Cognos 11 中显示数据标签值
- swift - 引用 Swift 包中的私有源 url
- javascript - IE 11-SCRIPT1002 中的 Word 加载项错误:polyfills.js 中的语法错误
- javascript - React-Native 大中间按钮被标签栏截断
- javascript - 当我“复制”一个文件时,我在哪里检索文件名和路径?
- jquery - 轮播控制按钮仅适用于一页
- algorithm - 将 StartIndex/EndIndex 转换为 PageNumber/PageSize