猿问

解码 json 包括 json 编码的字符串

嘿伙计们,我从外部 Api 获取 websocket 信息,它以这种方式给我 json 响应:


 `{"name":"message","args":["{\"method\":\"chatMsg\",\"params\":{\"channel\":\"channel\",\"name\":\"name\",\"nameColor\":\"B5B11E\",\"text\":\"<a href=\\\"https://play.spotify.com/browse\\\" target=\\\"_blank\\\">https://play.spotify.com/browse</a>\",\"time\":1455397119}}"]}`

我把它放到这个结构中


type main struct {


Name string `json:"name"`

Args []arg  `json:"args"`

}


type arg struct {

    Method string`json:"method"`

    Params par `json:"params"`

}

type par struct {

    Channel     string `json:"channel,omitempty"`

    Name        string `json:"name,omitempty"`

    NameColor   string `json:"nameColor,omitempty"`

    Text        string `json:"text,omitempty"`

    Time        int64  `json:"time,omitempty"`

}

并用代码解码


sReplace := strings.NewReplacer(`"{`, "{", `"]`, "]", "\\", ``)

strN := sReplace.Replace(str)

r := strings.NewReader(strN)

d := json.NewDecoder(r)

m := main{}

我收到错误


invalid character 'h' after object key:value pair

我知道错误是文本字段值的结果。有什么好的方法可以清理它或告诉解码器忽略文本字段的内容吗?


人到中年有点甜
浏览 231回答 1
1回答

慕妹3242003

应用程序正在解析包含子字符串的数据"text":"<a href="https。这不是有效的 JSON。错误消息是抱怨hin href。由于 JSON 值包括编码的 JSON 值,因此应用程序必须分两步进行解码:type main struct {&nbsp; Name string&nbsp; &nbsp;`json:"name"`&nbsp; Args []string `json:"args"`}type arg struct {&nbsp; Method string `json:"method"`&nbsp; Params par&nbsp; &nbsp; `json:"params"`}type par struct {&nbsp; Channel&nbsp; &nbsp;string `json:"channel,omitempty"`&nbsp; Name&nbsp; &nbsp; &nbsp; string `json:"name,omitempty"`&nbsp; NameColor string `json:"nameColor,omitempty"`&nbsp; Text&nbsp; &nbsp; &nbsp; string `json:"text,omitempty"`&nbsp; Time&nbsp; &nbsp; &nbsp; int64&nbsp; `json:"time,omitempty"`}str := `{"name":"message","args":["{\"method\":\"chatMsg\",\"params\":{\"channel\":\"channel\",\"name\":\"name\",\"nameColor\":\"B5B11E\",\"text\":\"<a href=\\\"https://play.spotify.com/browse\\\" target=\\\"_blank\\\">https://play.spotify.com/browse</a>\",\"time\":1455397119}}"]}`var m mainif err := json.Unmarshal([]byte(str), &m); err != nil {&nbsp; &nbsp; log.Fatal(err)}var args argif err := json.Unmarshal([]byte(m.Args[0]), &args); err != nil {&nbsp; &nbsp; log.Fatal(err)}
随时随地看视频慕课网APP

相关分类

Go
我要回答