Marshalling json.RawMessage: Deciphering Base64 Encoding
In an attempt to marshal a json.RawMessage object, you may encounter an unexpected base64 encoded string as output instead of the desired JSON string. To unravel this behavior, let's delve into the underlying concept.
json.RawMessage, as its name suggests, is designed to handle raw JSON data as a byte slice. When you attempt to marshal a RawMessage using json.Marshal, the default behavior is to encode it as if it were a regular []byte. This leads to the base64 encoding you observed.
To overcome this, the solution lies in passing a pointer to the RawMessage to json.Marshal. This is because RawMessage's MarshalJSON method, which is responsible for the marshaling process, expects a pointer as its argument. Without the pointer, it cannot correctly return the byte slice as intended.
By modifying your code to pass a pointer, as shown below, you will retrieve the expected JSON string as output:
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 Encode json.RawMessage as Base64?. For more information, please follow other related articles on the PHP Chinese website!