Json 意外字符 

标签 json powershell flutter character

我正在使用下面的代码使用 PowerShell 重新生成我的 Json,但是它在 json { 标记开始之前创建了意外的字符。

<#$data = Get-Content -Raw -Path myfile.json | ConvertFrom-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
}

$data | Select-Object -Property stations | ConvertTo-Json | Set-Content "testJson.json" -Encoding UTF8

enter image description here

上传后调用此文件时,由于该意外字符,我无法读取 json 文件。

希望有人可以在PowerShell代码中提供帮助,以确保不存在这样的字符,我可能正在做一些简单的事情,但不确定如何做。

我正在读取PowerShell到Flutter后生成的json文件,这会抛出如下所示的错误 enter image description here

谢谢

最佳答案

您需要找到一种方法让 Flutter 处理 UTF-8 字节顺序标记(0xEF 0xBB 0xBF),或者将文件写入不带 BOM 的 UTF8。

如果您使用的是 PowerShell 6 或更高版本,则可以使用

Set-Content "testJson.json" -Encoding utf8NoBOM

对于版本 6 以下的 PowerShell,该功能不可用,因此您可以使用

$json = $data | Select-Object -Property stations | ConvertTo-Json

# [System.IO.File]::WriteAllText() defaults to UTF8 without BOM
# use an absolute path here
[System.IO.File]::WriteAllText("D:\Test\testJson.json", $json)

关于Json 意外字符 ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63969957/

相关文章:

javascript - JSP 属性 JSON 对象在 Javascript 中删除转义字符

c# - 从单独的线程更新 cmdlet 进度的最佳方法

firebase - 在 Flutter 中使用 Firebase Messaging ^8.0.0-dev.8 收到通知时如何运行函数?

powershell - 尝试使用PowerShell获取进程数

powershell - Try-catch 问题 powershell

Flutter Web 无法使用移动项目中的包

android - 如何根据 Flutter 中的按钮单击上下移动一个小部件?

java - 将字段映射为键值对

java - Jackson JSON、不可变类和接口(interface)

jquery - 如何在 jQuery 中输出 JSON 列