You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell生成JSON含前置意外字符,Flutter读取失败求助

解决PowerShell生成JSON时的UTF-8 BOM问题

你遇到的字符其实是UTF-8字节顺序标记(BOM)的文本表示。PowerShell默认的UTF8编码会添加这个BOM,但Flutter在解析JSON时通常不期望有BOM,这就导致了读取错误。

要解决这个问题,我们需要生成无BOM的UTF-8格式JSON文件。下面是修改后的完整代码:

$data = @"
{
  "stations": [
    { "code": "1", "name": "United force" },
    { "code": "2", "name": "Toowoon Bay Service Station" }
  ],
  "prices": [
    { "stationcode": "1", "fueltype": "DL", "price": 126.97 },
    { "stationcode": "1", "fueltype": "E10", "price": 118.92 },
    { "stationcode": "2", "fueltype": "E10", "price": 112.90 },
    { "stationcode": "2", "fueltype": "P95", "price": 125.90 },
    { "stationcode": "2", "fueltype": "P98", "price": 155.90 },
    { "stationcode": "2", "fueltype": "U91", "price": 115.20 }
  ]
}
"@ | ConvertFrom-Json

foreach ($price in $data.prices) {
  $data.stations | Where-Object { $_.code -eq $price.stationcode } | Add-Member -MemberType NoteProperty -Name $price.fueltype -Value $price.price
}

# 根据你的PowerShell版本选择对应的输出方式:
# 如果你使用PowerShell 6及以上版本,可直接用Set-Content
# $data | Select-Object -Property stations | ConvertTo-Json | Set-Content "testJson.json" -Encoding utf8NoBOM

# 兼容PowerShell 5.1及更早版本,使用Out-File
$data | Select-Object -Property stations | ConvertTo-Json | Out-File "testJson.json" -Encoding utf8NoBOM

关键修改说明:

  • 替换了原来的Set-Content -Encoding UTF8为Out-File -Encoding utf8NoBOM(或PowerShell 6+的Set-Content -Encoding utf8NoBOM),这样生成的JSON文件就不会带有UTF-8 BOM了。
  • utf8NoBOM编码专门用于生成无BOM的UTF-8文件,完美适配Flutter等对BOM敏感的解析器。

测试一下生成的testJson.json,Flutter应该就能正常读取了!

内容的提问来源于stack exchange,提问作者Casper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 11:23:15