Unmarshalling Escaped JSON Strings with Go
When using Sockjs with Go, you may encounter issues parsing escaped JSON strings received from JavaScript clients as []byte. This can lead to error messages like "json: cannot unmarshal string into Go value". To resolve this issue, you can use a simple method to unescape the string before unmarshalling.
Using strconv.Unquote
strconv.Unquote() is a built-in Go function that removes escaped characters from a string. By applying it to the received JSON string, you can effectively unescape it.
Here's how you can do it:
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) }
In this example, the escaped JSON string is successfully unescaped using strconv.Unquote(), and the data is parsed into the Msg struct without errors.
The above is the detailed content of How to Unmarshall Escaped JSON Strings in Go?. For more information, please follow other related articles on the PHP Chinese website!