我的 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"
在我的输出文件中,我只得到“???”对于任何特殊字符。有谁知道如何让它在输出文件中显示特殊字符?
彼得·施奈德的有用回答 and 纳斯的有用回答两个地址one你的方法有问题:你需要:
-
要么: 访问.Content
返回的响应对象上的属性Invoke-WebRequest
得到实际的data返回(作为 JSON 字符串),然后您可以将其传递给ConvertFrom-Json
.
-
or: use Invoke-RestMethod
相反,它返回数据directly and 将其解析为自定义对象,因此您可以直接使用这些对象,而不需要ConvertTo-Json
;然而,对于字符编码问题,例如在本例中,这是not一个选项,因为需要对 JSON 字符串进行显式重新编码 - 见下文。
然而,你还有一个字符编码 problem,因为,在不存在charset
中的信息response header,PowerShell 将返回的 UTF-8 编码 JSON 字符串解释为ISO-8859-1-编码,在 Windows PowerShell 以及PowerShell(核心) 至 v7.3.3, except that v7.0+ 默认为 UTF-8JSON, 具体来说。
v7.4+将使用UTF-8 作为general default,即对于all媒体类型。
有两种可能的解决方案:
这是后者的实现:
# Note that there's no point in using
# -ContentType "application/json; charset=utf-8" in this case,
# as -ContentType only applies to data sent *to* the web service.
$request = 'http://151.80.109.18:8082/vrageremote/v1/session/players'
$a = Invoke-WebRequest $request
# $a.Content cannot be used, because it contains the *misinterpreted* JSON string,
# but $a.RawContentStream provides access to the raw bytes,
# which you can decode into a string with the encoding of choice.
$jsonCorrected =
[Text.Encoding]::UTF8.GetString(
$a.RawContentStream.ToArray()
)
# Now process the reinterpreted string.
$jsonCorrected |
ConvertFrom-Json |
Select -expand Data |
Select -expand players |
Select displayName, factionTag | Out-file "$scriptPath\getFactionTag.txt"
Note:
-
这个答案提供便利功能
ConvertTo-BodyWithEncoding
,它包装了上面的功能。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)