首页 > 解决方案 > Powershell - 大括号内大括号的 JSON 语法

问题描述

Powershell 5.1 - 我正在使用数据Invoke-RestMethodPOST端点。

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我不会收到任何错误。

标签: jsonpowershell

解决方案


您没有正确嵌套对象:

$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

推荐阅读