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

How to Unmarshall Escaped JSON Strings in Go with SockJS?

Patricia Arquette
Release: 2024-12-22 16:29:10
Original
678 people have browsed it

How to Unmarshall Escaped JSON Strings in Go with SockJS?

Unmarshalling Escaped JSON Strings

When employing Sockjs with Go, one may encounter challenges when JavaScript clients transmit JSON data as escaped strings. This can lead to parsing errors like "json: cannot unmarshal string into Go value of type main.Msg."

Solution

To circumvent this issue, pre-process the JSON string using strconv.Unquote. Here's how it works:

package main

import (
    "encoding/json"
    "fmt"
    "strconv"
)

type Msg struct {
    Channel string
    Name   string
    Msg     string
}

func main() {
    var msg Msg
    val := []byte(`"{\"channel\":\"buu\",\"name\":\"john\", \"msg\":\"doe\"}"`)

    s, _ := strconv.Unquote(string(val))

    // Unmarshal the unquoted JSON string
    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, we use strconv.Unquote to remove the escape characters from the JSON string. Once unquoted, we proceed to unmarshal it into the Msg struct. This approach resolves the parsing error and allows us to access the data correctly.

The above is the detailed content of How to Unmarshall Escaped JSON Strings in Go with SockJS?. 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