Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Marshalling json.RawMessage returns base64 encoded string

Tags:

json

go

I run the following code:

package main  import (     "encoding/json"     "fmt" )  func main() {     raw := json.RawMessage(`{"foo":"bar"}`)     j, err := json.Marshal(raw)     if err != nil {         panic(err)     }     fmt.Println(string(j))   } 

Playground: http://play.golang.org/p/qbkEIZRTPQ

Output:

"eyJmb28iOiJiYXIifQ==" 

Desired output:

{"foo":"bar"} 

Why does it base64 encode my RawMessage as if it was an ordinary []byte?

After all, RawMessage's implementation of MarshalJSON is just returning the byte slice

// MarshalJSON returns *m as the JSON encoding of m. func (m *RawMessage) MarshalJSON() ([]byte, error) {     return *m, nil  } 
like image 726
ANisus Avatar asked Jun 15 '14 11:06

ANisus


People also ask

What does JSON Marshal do?

We can use the Marshal function to convert Go objects to JSON. The Marshal function comes with the following syntax. It accepts an empty interface. In other words, you can provide any Go data type to the function — an integer, float, string, struct, map, etc.

How do I use 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.

How do I encode JSON in Golang?

To encode JSON data we use the Marshal function. Only data structures that can be represented as valid JSON will be encoded: JSON objects only support strings as keys; to encode a Go map type it must be of the form map[string]T (where T is any Go type supported by the json package).

What is JSON marshalling and Unmarshalling Golang?

In Golang, struct data is converted into JSON and JSON data to string with Marshal() and Unmarshal() method. The methods returned data in byte format and we need to change returned data into JSON or String. In our previous tutorial, we have explained about Parsing JSON Data in Golang.


1 Answers

Found the answer in a go-nuts thread

The value passed to json.Marshal must be a pointer for json.RawMessage to work properly:

package main  import (     "encoding/json"     "fmt" )  func main() {     raw := json.RawMessage(`{"foo":"bar"}`)     j, err := json.Marshal(&raw)     if err != nil {         panic(err)     }     fmt.Println(string(j))   } 
like image 124
ANisus Avatar answered Sep 21 '22 17:09

ANisus