通过批处理脚本curl获取无BOM的UTF-8 JSON而非UTF-16 LE文件
解决方案:生成无BOM UTF-8 JSON 或移除BOM编码
一、直接修改批处理生成无BOM UTF-8文件
问题根源是PowerShell默认用UTF-16 LE带BOM编码处理重定向输出,和curl无关。可以通过以下两种方式调整:
方式1:用Out-File指定编码
替换原命令为:
powershell -Command "curl.exe -k -S -X GET -H 'Version: 16.0' -H 'Accept: application/json' 'https://IntendedURL' | Out-File -FilePath result.json -Encoding utf8NoBOM"
utf8NoBOM参数会强制输出不带BOM的UTF-8格式。
方式2:先设置PowerShell输出编码
通过临时修改PowerShell的输出编码,让重定向默认使用无BOM UTF-8:
powershell -Command "$OutputEncoding = [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); curl.exe -k -S -X GET -H 'Version: 16.0' -H 'Accept: application/json' 'https://IntendedURL' > result.json"
[System.Text.UTF8Encoding]::new($false)表示创建不带BOM的UTF-8编码实例。
二、移除已存在文件的BOM编码
如果已经生成了带BOM的JSON文件,可直接用PowerShell批处理命令移除BOM:
powershell -Command "(Get-Content result.json -Raw) | Set-Content result.json -Encoding utf8NoBOM"
Get-Content -Raw会读取整个文件内容并跳过BOM标识,再通过Set-Content以无BOM UTF-8格式重新写入。
内容的提问来源于stack exchange,提问作者cyborg1234
相关产品推荐
相关产品推荐

