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.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • douju4278 2018-10-29 14:56
    关注

    You can replace \x with \\x using string.Replace() function. Then, Unmarshal the replaced string. Here is a working example.

    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 c++类和数组实验代码
  • ¥20 C语言字符串不区分大小写字典排序相关问题
  • ¥15 关于#python#的问题:我希望通过逆向技术爬取1688搜索页下滑加载的数据
  • ¥15 关于Linux的终端里,模拟实现一个带口令保护的屏保程序遇到的输入输出的问题!(语言-c语言)
  • ¥15 请问,这个嵌入式Linux系统怎么分析,crc检验区域在哪
  • ¥15 二分类改为多分类问题
  • ¥15 Unity微信小游戏上调用ReadPixels()方法报错
  • ¥15 如何通过求后验分布求得样本中属于两种物种其中一种的概率?
  • ¥15 q从常量变成sin函数,怎么改写python代码?
  • ¥15 图论编程问题,有可以指导的吗