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 }
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.
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.
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).
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.
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)) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With