Reputation: 2417
I have a script that gets data from a public API. I try to parse a value from the Json response into a variable. However it seems that when I Write-Host
the variable it has replaced — with â.
Code:
$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
Output:
Artifact Creature — Construct
Upvotes: 1
Views: 526
Reputation: 61178
It looks like the strings returned by the Invoke-RestMethod here are encoded in 'ISO-8859-1' and not as you would expect in UTF-8.
This means you need to convert to UTF-8 where needed, something like this:
$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
Output
Artifact Creature — Construct
To convert the whole json to UTF-8, You could use Invoke-WebRequest
rather than 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
Upvotes: 3