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

How to Unmarshal Escaped JSON Strings in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-12-27 16:35:09878browse

How to Unmarshal Escaped JSON Strings in Go?

Unmarshaling Escaped JSON Strings in Go

When using SockJS with Go, parsing JSON data sent from a JavaScript client as a byte slice can be troublesome. The server receives the escaped JSON, but attempts to parse it as an ordinary string, leading to the error "json: cannot unmarshal string into Go value of type main.Msg".

The solution lies in utilizing the strconv.Unquote function before attempting to unmarshal the JSON. This function removes the escape characters, leaving you with a string that can be parsed into a Go value.

Here's a modified example:

package main

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)
}

Output:

{"channel":"buu","name":"john", "msg":"doe"}
<nil>
buu john doe

The above is the detailed content of How to 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