Home > database >  "Unexpected token" or "JSON parse error - trailing comma" when doing API call wi
"Unexpected token" or "JSON parse error - trailing comma" when doing API call wi

Time:12-22

I have the following PowerShell API script:

$VMname = "abcd"
$IP_address = '2.2.2.2'

$url = "https://ansibletower.xyz.com/api/v2/job_templates/12321/launch/"
$token = "9998980fsfdfsdfdf"
$headers = @{Authorization = "Bearer $token"}
$contentType = "application/json"
$method = "POST"

#### $body = '{"extra_vars": {"vm_name": "abc", "vm_ip_address": "2.2.2.2"}}'
$body = '{"extra_vars":{"vm_name":'$VMname', "vm_ip_address":'$IP_address'}}'

Invoke-RestMethod -ContentType "$contentType" -Uri $url -Method $method -Headers $headers -Body $body 

When I try it with manually predefined values in the body (see the commented body line above) - it works. But when I try it with variables $VMname and $IP_address, I get the error:

Unexpected token '$VMname', "vm_ip_address":'$IP_address'}}'' expression or statement.

And if I remove single quotes before and after variables VMname and IP_address I get:

{"detail":"JSON parse error - Expecting value: line 1 column...Possible cause: trailing comma."}

It is obviously a problem with syntax and / or formatting but I cannot find the solution. Does anyone know?

CodePudding user response:

Use ConvertTo-Json for this:

$VMname = "abcd"
$IP_address = '2.2.2.2'
$body = ConvertTo-Json -Compress -Depth 9 @{
    extra_vars = @{
        vm_name = $VMname
        vm_ip_address = $IP_address
    }
}

$Body
{"extra_vars":{"vm_name":"abcd","vm_ip_address":"2.2.2.2"}}

Btw, it is probably not even required to serialize your body to Json as Invoke-Restmethod is supposed to take care of that:

-body

When the input is a POST request and the body is a String, the value to the left of the first equals sign (=) is set as a key in the form data and the remaining text is set as the value. To specify multiple keys, use an IDictionary object, such as a hash table, for the Body.

  • Related