When employing Sockjs with Go, one may encounter challenges when JavaScript clients transmit JSON data as escaped strings. This can lead to parsing errors like "json: cannot unmarshal string into Go value of type main.Msg."
To circumvent this issue, pre-process the JSON string using strconv.Unquote. Here's how it works:
package main import ( "encoding/json" "fmt" "strconv" ) type Msg struct { Channel string Name string Msg string } func main() { var msg Msg val := []byte(`"{\"channel\":\"buu\",\"name\":\"john\", \"msg\":\"doe\"}"`) s, _ := strconv.Unquote(string(val)) // Unmarshal the unquoted JSON string err := json.Unmarshal([]byte(s), &msg) fmt.Println(s) fmt.Println(err) fmt.Println(msg.Channel, msg.Name, msg.Msg) }
In this example, we use strconv.Unquote to remove the escape characters from the JSON string. Once unquoted, we proceed to unmarshal it into the Msg struct. This approach resolves the parsing error and allows us to access the data correctly.
The above is the detailed content of How to Unmarshall Escaped JSON Strings in Go with SockJS?. For more information, please follow other related articles on the PHP Chinese website!