How use curl with spaces in json

When making a POST call with curl I'm having trouble getting the JSON data to be passed correctly. The string is cut off at the first whitespace/blank space.

My call looks like this, I'm executing through a powershell script that has two parameters. Using these parameters I concatenate the JSON that is used for the call.

I input for instance 854e-ae7686fbc75a 365 as parameters

# usage: powershell -file send.ps1 [apitoken] [interval]

param (
    [string]$apitoken = "",
    [int]$startInterval = "365"
)

$AUTHORIZATION = $apitoken
$STARTDATE = (Get-Date).AddDays(-$startInterval)
$ENDDATE = (Get-Date)
$JSON = '{"ApiToken":"' + $AUTHORIZATION + '",' +
    '"StartDate":"' + $STARTDATE + '",' +
    '"EndDate":"' + $ENDDATE + '",' +
    '"Type":"SalesExport"' +
    '}'

$CURLEXE = '..bincurl.exe'
$CurlArgument = '-X', 'POST',
                '-m', 7200,
                '-H', '"Content-Type:application/json"',
                '-d', $JSON,
                'https://my.server/export/sales'

& $CURLEXE @CurlArgument

The STARTDATE would then be the current date minus 365 days. ENDDATE would be the current date.

The problem is as soon as there is a blank space (or possibly any whitespace) in the JSON variable curl thinks that the JSON has ended and says that the JSON is unterminated. There is no difference if I surround the variable with single or double quotes.

Even if the whitespace is inside one of the two DateTime variables the problem occurs!

How can I format the JSON properly so that it can include whitespace?


Not a direct answer to your question, but since you're using PowerShell anyway: why not use the native Invoke-WebRequest instead of an external command?

$today   = (Get-Date).Date
$uri     = 'https://example.org/export/sales'
$headers = @{
    'Content-Type' = 'application/json'
}
$data    = @{
    'ApiToken'  = $apitoken
    'StartDate' = $today.AddDays(-$startInterval).ToString('d')
    'EndDate'   = $today.ToString('d')
    'Type'      = 'SalesExport'
} | ConvertTo-Json

Invoke-WebRequest -Method Post -Headers $headers -Body $data -Uri $uri

Alternatively you can define the JSON data as a multiline string:

$startDate = $today.AddDays(-$startInterval).ToString('d')
$endDate   = $today.ToString('d')
$data = @"
{
    "ApiToken": "$apitoken",
    "StartDate": "$startDate",
    "EndDate": "$endDate",
    "Type": "SalesExport"
}
"@
链接地址: http://www.djcxy.com/p/48622.html

上一篇: 如何将文件上传到WCF服务?

下一篇: 如何在json中使用空格卷曲