Home > Article > Backend Development > Why does marshalling a json.RawMessage value result in a base64-encoded string instead of raw JSON?
Marshalling json.RawMessage Returns Base64-Encoded String
Question:
When marshalling a json.RawMessage value, why is the output a base64-encoded string instead of the raw JSON?
Background:
The code below demonstrates the issue:
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)) }
Expected Output:
{"foo":"bar"}
Actual Output:
"eyJmb28iOiJiYXIifQ=="
Answer:
The json.RawMessage type's MarshalJSON method simply returns the underlying byte slice. However, for json.RawMessage to work properly, the value passed to json.Marshal must be a pointer.
Solution:
To fix the issue, update the code as follows:
j, err := json.Marshal(&raw)
The above is the detailed content of Why does marshalling a json.RawMessage value result in a base64-encoded string instead of raw JSON?. For more information, please follow other related articles on the PHP Chinese website!