Powershell Json替换为–

问题描述

我有一个脚本,可从公共API获取数据。我尝试将Json响应中的值解析为变量。但是,当我Write-Host变量似乎已被替换为â。

代码

$SetData = Invoke-RestMethod -Uri "https://mtgjson.com/api/v5/2XM.json" -ContentType "application/json" -Method GET

$Card = $SetData.data.cards | Where-Object { $_.name -eq "Adaptive Automaton" -and $_.isPromo -ne "true"}
Write-Host $Card.type -ForegroundColor Cyan

输出

Artifact Creature — Construct

解决方法

看起来这里Invoke-RestMethod返回的字符串是在'ISO-8859-1'中编码的,而不是在UTF-8中所期望的。

这意味着您需要在需要时转换为UTF-8,如下所示:

$encoding = [System.Text.Encoding]::GetEncoding('ISO-8859-1')

$SetData = Invoke-RestMethod -Uri "https://mtgjson.com/api/v5/2XM.json" -ContentType "application/json" -Method GET

$Card = $SetData.data.cards | Where-Object { $_.name -eq "Adaptive Automaton" -and !$_.isPromo}
# convert the string in '$Card.type' from encoding 'ISO-8859-1' into 'UTF-8'
$cardType = ([System.Text.Encoding]::UTF8).GetString($encoding.GetBytes($Card.type))

Write-Host $cardType -ForegroundColor Cyan

输出

Artifact Creature — Construct

要将整个json转换为UTF-8,可以使用Invoke-WebRequest而不是Invoke-RestMethod

$encoding = [System.Text.Encoding]::GetEncoding('ISO-8859-1')

$SetData = Invoke-WebRequest -Uri "https://mtgjson.com/api/v5/2XM.json" -Method Get
# convert $SetData.Content to UTF-8 and convert that from JSON
$content = ([System.Text.Encoding]::UTF8).GetString($encoding.GetBytes($SetData.Content)) | ConvertFrom-Json

$Card = $content.data.cards | Where-Object { $_.name -eq "Adaptive Automaton" -and !$_.isPromo}
Write-Host $Card.type -ForegroundColor Cyan