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
To parse JSON, we use the Unmarshal() function in package encoding/json to unpack or decode the data from JSON to a struct. Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. Note: If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError.
To unmarshal a JSON array into a slice, Unmarshal resets the slice length to zero and then appends each element to the slice. As a special case, to unmarshal an empty JSON array into a slice, Unmarshal replaces the slice with a new empty slice.
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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With