You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PowerShell的Invoke-RestMethod提取多语言JSON数据时乱码问题

解决PowerShell调用DeepL API返回乱码问题

我用PowerShell写脚本调用DeepL API翻译多语言(法语、韩语、日语等含特殊字符的语言),但返回结果一直乱码,示例如下:

{
    "Hello":  "ìë\u0085íì¸ì",
    "World":  "ì¸ê³"
}

原代码如下:

function translate($text) {
    $headers = @{
        "Authorization" = "DeepL-Auth-Key ...."
        "Accept-Charset" = "utf-8"
    }
    $body = @{
        "text" = "$text"
        "target_lang" = "KO"
    }
    $response = Invoke-RestMethod -Uri "https://api-free.deepl.com/v2/translate" `
        -Method Post `
        -Headers $headers `
        -ContentType "application/x-www-form-urlencoded" `
        -Body $body `

    return $response.translations.text
}

$wordList = @("Hello", "World")

$translations = @{}

foreach ($word in $wordList) {
    $translation = translate $word
    $translations[$word] = $translation
}

$translations | ConvertTo-Json | Out-File "ko.json" -Encoding utf8

我试过调整请求头、请求体、Out-File的编码参数,甚至替换Invoke-RestMethod,起初都没解决问题。

修正后的代码

改用Invoke-WebRequest替代Invoke-RestMethod,手动处理响应的UTF-8编码:

function translate($text) {
    $headers = @{
        "Authorization" = "DeepL-Auth-Key ...."
        "Accept-Charset" = "utf-8"
    }
    $body = @{
        "text" = "$text"
        "target_lang" = "KO"
    }
    $response = Invoke-WebRequest `
            -Uri "https://api-free.deepl.com/v2/translate" `
            -Method Post `
            -Headers $headers `
            -ContentType "application/x-www-form-urlencoded" `
            -Body $body `

    $encodedResponse = [Text.Encoding]::UTF8.GetString($response.RawContentStream.ToArray())
    $jsonResponse = $encodedResponse | ConvertFrom-Json
    $translation = $jsonResponse.translations.text
    return $translation
}

$wordList = @("Hello", "World")

$translations = @{}

foreach ($word in $wordList) {
    $translation = translate $word
    $translations[$word] = $translation
}

$translations | ConvertTo-Json | Out-File "ko.json" -Encoding utf8

原因说明

Invoke-RestMethod在处理部分API的UTF-8响应时,可能会错误地使用系统默认编码解析,导致非ASCII字符乱码。改用Invoke-WebRequest后,直接读取原始响应流并用UTF-8编码解析,就能正确识别韩语、日语等含特殊字符的语言翻译结果。

内容的提问来源于stack exchange,提问作者tenshi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 00:46:21