Powershell ConvertFrom Json编码特殊字符问题

Powershell ConvertFrom Json编码特殊字符问题,powershell,character-encoding,invoke-webrequest,Powershell,Character Encoding,Invoke Webrequest,我的powershell脚本中有这段代码,但它在特殊角色部分表现不佳 $request = 'http://151.80.109.18:8082/vrageremote/v1/session/players' $a = Invoke-WebRequest -ContentType "application/json; charset=utf-8" $request | ConvertFrom-Json | Select -expand Data | Select -expand

我的powershell脚本中有这段代码,但它在特殊角色部分表现不佳

 $request = 'http://151.80.109.18:8082/vrageremote/v1/session/players'
 $a = Invoke-WebRequest -ContentType "application/json; charset=utf-8" $request |
 ConvertFrom-Json    |
 Select -expand Data |
 Select -expand players |
 Select displayName, factionTag | Out-file "$scriptPath\getFactionTag.txt"

在我的输出文件中,对于任何特殊字符,我只得到“??”。有人知道如何让它在输出文件中显示特殊字符吗?

尝试将
.Content
属性的值转换为JSON:

$request = 'http://151.80.109.18:8082/vrageremote/v1/session/players'
$a = Invoke-WebRequest -ContentType "application/json; charset=utf-8" $request

($a.Content | convertfrom-json).Data.Players | select DisplayName,FactionTag | Out-file "$scriptPath\getFactionTag.txt" -Encoding Default

如果您只需要json数据,而不需要
ParsedHtml
标题以及
Invoke WebRequest
返回的其他对象,请使用
Invoke RestMethod

$request = 'http://151.80.109.18:8082/vrageremote/v1/session/players'
$a = Invoke-RestMethod -ContentType "application/json; charset=utf-8" $request |
Select -expand Data |
Select -expand players |
Select displayName, factionTag | Out-file "$scriptPath\getFactionTag.txt"
这两种方法都解决了一个问题:您需要:

  • 或者:访问
    Invoke WebRequest
    返回的响应对象上的
    .Content
    属性,以获取返回的实际数据(作为JSON字符串),然后将其传递给
    ConvertFrom JSON

  • 或者:改用
    调用RestMethod
    ,它直接返回数据并将其解析为自定义对象,因此您可以直接使用这些对象,而无需
    转换为Json
    ;但是,对于字符编码问题,例如在本例中,这不是一个选项,因为需要显式地重新编码JSON字符串-请参阅下文

但是,您仍然存在字符编码问题,因为在响应头中缺少
字符集
信息的情况下,PowerShell将返回的UTF-8编码JSON字符串解释为-encoded(从PowerShell 7.0起仍然适用)

有两种可能的解决方案(除了切换到PowerShell Core):

  • 优选地,修改web服务以在响应头的
    ContenType
    字段中包括
    charset=utf-8

  • 如果不能这样做,则必须显式地对接收到的字符串重新编码,以纠正字符编码错误

下面是后者的实现:

$request = 'http://151.80.109.18:8082/vrageremote/v1/session/players'
$a = Invoke-WebRequest -ContentType "application/json; charset=utf-8" $request

# $a.Content now contains the *misinterpreted* JSON string, so we must 
# obtain its byte representation and re-interpret the bytes as UTF-8.
# Encoding 28591 represents the ISO-8859-1 encoding - see https://docs.microsoft.com/en-us/windows/desktop/Intl/code-page-identifiers
$jsonCorrected = [Text.Encoding]::UTF8.GetString(
  [Text.Encoding]::GetEncoding(28591).GetBytes($a.Content)
)

# Now process the reinterpreted string.
$jsonCorrected |
  ConvertFrom-Json    |
  Select -expand Data |
  Select -expand players |
  Select displayName, factionTag | Out-file "$scriptPath\getFactionTag.txt"

这就去掉了“??”字符,但现在我只剩下很多“Д。像“УПА”变成“ÐÐД一样,与上面的结果相同,这去掉了“??”字符,但现在我剩下了很多“Д。像“УПА”变成“ÐÐД,这通常是有用的建议,但这里的问题是字符编码,因此需要在进一步处理之前对接收到的字符串数据执行显式重新编码,因此,在这种特殊情况下,需要使用
Invoke WebRequest
响应的
.Content
属性。