如何解组转义的JSON字符串 [英] How to unmarshal an escaped JSON string
本文介绍了如何解组转义的JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Go中使用Sockjs,但是当JavaScript客户端将json发送到服务器时,它将转义它,并以[] byte的形式发送它.我试图弄清楚如何解析json,以便我可以读取数据.但我收到此错误.
I am using Sockjs with Go, but when the JavaScript client send json to the server it escapes it, and send's it as a []byte. I'm trying to figure out how to parse the json, so that i can read the data. but I get this error.
json:无法将字符串解组为main.Msg类型的Go值
json: cannot unmarshal string into Go value of type main.Msg
我该如何解决? html.UnescapeString()
无效.
val, err := session.ReadMessage()
if err != nil {
break
}
var msg Msg
err = json.Unmarshal(val, &msg)
fmt.Printf("%v", val)
fmt.Printf("%v", err)
type Msg struct {
Channel string
Name string
Msg string
}
//Output
"{\"channel\":\"buu\",\"name\":\"john\", \"msg\":\"doe\"}"
json: cannot unmarshal string into Go value of type main.Msg
推荐答案
您可能想使用 strconv.Unquote
:)
You might want to use strconv.Unquote
on your JSON string first :)
这是一个示例,由@gregghz提供:
Here's an example, kindly provided by @gregghz:
package main
import (
"encoding/json"
"fmt"
"strconv"
)
type Msg struct {
Channel string
Name string
Msg string
}
func main() {
var msg Msg
var val []byte = []byte(`"{\"channel\":\"buu\",\"name\":\"john\", \"msg\":\"doe\"}"`)
s, _ := strconv.Unquote(string(val))
err := json.Unmarshal([]byte(s), &msg)
fmt.Println(s)
fmt.Println(err)
fmt.Println(msg.Channel, msg.Name, msg.Msg)
}
这篇关于如何解组转义的JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文