我的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"在我的输出文件中,我只得到‘?’用于任何特殊字符。有人知道如何让它在我的输出文件中显示特殊字符吗?
发布于 2018-10-29 02:05:09
Peter Schneider's helpful answer和Nas' helpful answer都解决了您的方法的一个问题:您需要:
JSON
Invoke-WebRequest返回的response对象上的.Content属性,以获取返回的实际数据(以JSON字符串的形式),然后可以将其传递给Invoke-RestMethod,它直接返回数据并将其解析为自定义对象,因此您可以直接使用这些对象,而不需要ConvertTo-Json;但是,对于字符编码问题,例如在本例中,这不是一个选项,因为需要显式地重新编码JSON字符串-请参见下文。但是,由于在character-encoding charset响应<>E229<>E130头中缺少信息,PowerShell会将返回的UTF-8编码的JSON字符串解释为编码的(从PowerShell 7.0开始仍然适用)。
有两种可能的解决方案:
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"发布于 2018-10-29 00:19:06
尝试将.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发布于 2018-10-29 00:31:24
如果只需要json数据而不需要ParsedHtml、Headers和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"https://stackoverflow.com/questions/53033242
复制相似问题