Home  >  Article  >  Backend Development  >  Why does json.Marshal with json.RawMessage return a Base64 encoded string?

Why does json.Marshal with json.RawMessage return a Base64 encoded string?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-12 08:04:02490browse

Why does json.Marshal with json.RawMessage return a Base64 encoded string?

Marshalling json.RawMessage Returns 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn