gpt4 book ai didi

json - Powershell Json 替换 — 用 â

转载 作者:行者123 更新时间:2023-12-03 00:56:01 26 4
gpt4 key购买 nike

我有一个从公共(public) 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

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

关于json - Powershell Json 替换 — 用 â,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63438068/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com