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

How to Unmarshall Escaped JSON Strings in Go?

Patricia Arquette
Release: 2024-12-26 16:55:14
Original
801 people have browsed it

How to Unmarshall Escaped JSON Strings in Go?

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)
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template