Home > Article > Backend Development > Why does json.Marshal with json.RawMessage return a Base64 encoded string?
When calling json.Marshal with a json.RawMessage value, the result is unexpected. Instead of the desired JSON string, a base64 encoded string is returned.
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)) // Output: "eyJmb28iOiJiYXIifQ==" }
The issue lies in the usage of json.RawMessage in json.Marshal. The json.RawMessage type, designed to store raw JSON data without decoding it, has a MarshalJSON method that simply returns the byte slice.
func (m *RawMessage) MarshalJSON() ([]byte, error) { return *m, nil }
However, for json.Marshal to function correctly with json.RawMessage, the value passed must be a pointer to the json.RawMessage instance.
j, err := json.Marshal(&raw)
By passing a pointer to json.RawMessage, the MarshalJSON method is invoked on the pointer, ensuring that the byte slice is returned without base64 encoding.
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)) // Output: "{"foo":"bar"}" }
The above is the detailed content of Why does json.Marshal with json.RawMessage return a Base64 encoded string?. For more information, please follow other related articles on the PHP Chinese website!