我正在PowerShell7.4中创建一个JSON文件,以发送到第三方REST端点.Out-File
默认为UTF-8,当我在notepad++ 中判断文件时,编码设置显示为UTF-8.不幸的是,这篇帖子被拒绝了,并发了一条消息:
400 Bad Request
JSON parse error
Nested exception is com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 start byte 0xa0\n at line: 9259, column: 38
我判断了错误消息中指定的JSON行. 源JSON文件在其公司名称中有一个NO-BREAK SPACE序列,如下所示:
String Hex
------------ --------------------------------------
"Acme, Inc." 22 41 63 6d 65 2c c2 a0 49 6e 63 2e 22
UTF-8中的NO-BREAK SPACE显示为两个字节:0xc2 0xa0
.这两个字符都出现在JSON文件中,但该错误表明远程解析器没有将第一个字符作为序列的一部分进行处理.
以下是PowerShell脚本:
# identify CSV file
$csvFile = Get-ChildItem -Path ($path + '*.csv') -File |
Sort-Object LastWriteTime |
Select-Object -First 1
# suppress blank lines
$objData = Get-Content $csvFile -Encoding UTF8 |
Where-Object { $_ } |
ConvertFrom-CSV
# convert to JSON and save to file
$body = $objData |
ConvertTo-Json -Depth 100
$body |
Out-File ( $path + 'data.json')
# post JSON
$webParam = @{
Uri = $url
Method = 'POST'
Headers = @{ 'Authorization' = $auth
'Cache-Control' = 'no-cache' }
Body = $body
ContentType = 'application/json'
}
$apiResponse = Invoke-WebRequest @webParam
每次脚本运行时,数据通常都不同. 在大多数情况下,远程站点将毫无问题地接受JSON,因为它没有任何奇怪的Unicode字符.
我不确定为什么远程站点不喜欢这个字符串,但如果它不能区分整个两个字节的序列,那么这个错误是有意义的.在我发送之前,PowerShell的Test-JSON
cmdlet总是计算为True.以前有没有人遇到过这种情况?