dsaff82024 2018-10-29 02:47
浏览 65
已采纳

由于编码,解组返回空白对象

I'm attempting to unmarshal a raw json string. There seems to be an error with encoding but I can't quite figure it out.

package main

import (
    "encoding/json"
    "fmt"
    "log"
)

type Foo struct {
    Transmission string `json:"transmission"`
    Trim         string `json:"trim"`
    Uuid         string `json:"uuid"`
    Vin          string `json:"vin"`
}

func main() {

    var foo Foo

    sample := `{
        "transmission": "continuously\x20variable\x20automatic",
        "trim": "SL",
        "uuid" : "6993e4090a0e0ae80c59a76326e360a1",
        "vin": "5N1AZ2MH6JN192059"
    }`

    err := json.Unmarshal([]byte(sample), &foo)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(foo)

}

2009/11/10 23:00:00 invalid character 'x' in string escape code

It works if transmission entry is removed.

Here is a working playground.

  • 写回答

2条回答 默认 最新

  • douliao8402 2018-10-29 02:59
    关注

    Your input is not valid JSON. The JSON spec states that

    All code points may be placed within the quotation marks except for the code points that must be escaped: quotation mark (U+0022), reverse solidus (U+005C), and the control characters U+0000 to U+001F.

    Additionally, although there are two-character escape sequences, \x is not one of them, and thus it is being correctly interpreted as an invalid escape sequence by the Go parser. If you want to have a backslash literal in your JSON, it needs to be represented by \\ in the JSON input itself. See a modified version of your example: https://play.golang.org/p/JZdPJGpPR5q

    (note that this is not an issue with your Go string literal since you're already using a raw (``) string literal—the JSON itself needs to have two backslashes.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算