Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unmarshal an escaped JSON string

Tags:

json

go

sockjs

I am using Sockjs with Go, but when the JavaScript client send json to the server it escapes it, and send's it as a []byte. I'm trying to figure out how to parse the json, so that i can read the data. but I get this error.

json: cannot unmarshal string into Go value of type main.Msg

How can I fix this? html.UnescapeString() has no effect.

val, err := session.ReadMessage() if err != nil { break } var msg Msg  err = json.Unmarshal(val, &msg)  fmt.Printf("%v", val) fmt.Printf("%v", err)  type Msg struct {     Channel string     Name    string     Msg     string } 
//Output "{\"channel\":\"buu\",\"name\":\"john\", \"msg\":\"doe\"}" json: cannot unmarshal string into Go value of type main.Msg 
like image 238
Robin Westerlundh Avatar asked May 30 '13 22:05

Robin Westerlundh


People also ask

How do I Unmarshal JSON?

To parse JSON, we use the Unmarshal() function in package encoding/json to unpack or decode the data from JSON to a struct. Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. Note: If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError.

What does it mean to Unmarshal JSON?

To unmarshal a JSON array into a slice, Unmarshal resets the slice length to zero and then appends each element to the slice. As a special case, to unmarshal an empty JSON array into a slice, Unmarshal replaces the slice with a new empty slice.


1 Answers

You might want to use strconv.Unquote on your JSON string first :)

Here's an example, kindly provided by @gregghz:

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) } 
like image 168
fresskoma Avatar answered Oct 11 '22 21:10

fresskoma