Robin Westerlundh Robin Westerlundh - 4 months ago 15
JSON Question

How to unmarshal an escaped JSON string in Go?

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: cannot unmarshal string into Go value of type main.Msg

How can i fix this? html.UnescapeString() have no effect :/

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

Answer

You might want to use strconv.Unquote on your JSON string first :)

Comments