为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
人到中年有点甜 2021-12-13 18:20:07
嘿伙计们,我从外部 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我知道错误是文本字段值的结果。有什么好的方法可以清理它或告诉解码器忽略文本字段的内容吗?
查看完整描述

1 回答

?
慕妹3242003

TA贡献1824条经验 获得超6个赞

应用程序正在解析包含子字符串的数据"text":"<a href="https。这不是有效的 JSON。错误消息是抱怨hin href。


由于 JSON 值包括编码的 JSON 值,因此应用程序必须分两步进行解码:


type main struct {

  Name string   `json:"name"`

  Args []string `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"`

}


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 main

if err := json.Unmarshal([]byte(str), &m); err != nil {

    log.Fatal(err)

}

var args arg

if err := json.Unmarshal([]byte(m.Args[0]), &args); err != nil {

    log.Fatal(err)

}


查看完整回答
反对 回复 2021-12-13
  • 1 回答
  • 0 关注
  • 230 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号