Home >Backend Development >Golang >How to Unmarshal Escaped JSON Strings in Go?
When using SockJS with Go, parsing JSON data sent from a JavaScript client as a byte slice can be troublesome. The server receives the escaped JSON, but attempts to parse it as an ordinary string, leading to the error "json: cannot unmarshal string into Go value of type main.Msg".
The solution lies in utilizing the strconv.Unquote function before attempting to unmarshal the JSON. This function removes the escape characters, leaving you with a string that can be parsed into a Go value.
Here's a modified example:
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) }
Output:
{"channel":"buu","name":"john", "msg":"doe"} <nil> buu john doe
The above is the detailed content of How to Unmarshal Escaped JSON Strings in Go?. For more information, please follow other related articles on the PHP Chinese website!