jsongosockjs

How to unmarshal an escaped JSON string


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

How can I fix this? html.UnescapeString() has 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

Solution

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

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