Unescaping JSON Strings for Unmarshaling
When working with Sockjs and Go, you may encounter issues parsing JSON strings sent from a JavaScript client due to escaping. The JavaScript client may escape the strings and send them as []byte, leading to unmarshaling difficulties.
To resolve this, you can utilize the strconv.Unquote function to remove the escaping from the JSON string. This function takes a string as an argument and returns an unescaped version.
Solution:
import ( "encoding/json" "fmt" "strconv" ) // Code goes here. 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 Safely Unmarshal Escaped JSON Strings in Go?. For more information, please follow other related articles on the PHP Chinese website!