Home >Backend Development >Golang >How to Safely Unmarshal Escaped JSON Strings in Go?

How to Safely Unmarshal Escaped JSON Strings in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-31 10:09:10216browse

How to Safely Unmarshal Escaped JSON Strings in Go?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn