Home > OS >  Need to get a value in single quotes in the body section while calling a restapi through powershell
Need to get a value in single quotes in the body section while calling a restapi through powershell

Time:10-21

I'm using below script to call a RestAPi using powershell:

$cd = 12000
$Url = 'https://exampleSet/Set'
$Body = @{
    OperationType = 'new'
    Number = "'$($cd)'"
    CdAspId = 'Z_CK_BUGFIX'
    CdType = 'CA_106_4'
} | ConvertTo-Json

$headers = @{
'ContentType' = 'application/json'
'Accept' = 'application/json'
'APIKey' = 'abcdef'
}
Invoke-RestMethod -contentType "application/json" -Uri $url -Method Post -body $Body -Headers $headers

While execution, powershell task in Azure is showing me internal server error. I need help in passing the value in the body as:

Number = '12000'

How can I get the values in body in single quotes. Please help in this.

CodePudding user response:

As mentioned in the comments, JSON exclusively uses double-quoted string literals, so trying to create a JSON document with a property entry Number = '12000' doesn't make any sense - it wouldn't be valid JSON.

To force string encoding rather than a numerical value, simply surround the value with double-quotes in PowerShell:

$Body = @{
    OperationType = 'new'
    Number = "$cd"
    CdAspId = 'Z_CK_BUGFIX'
    CdType = 'CA_106_4'
} | ConvertTo-Json
  • Related