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

Mary-Kate Olsen
Release: 2024-11-12 08:04:02
Original
459 people have browsed it

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=="
}
Copy after login

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
}
Copy after login

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)
Copy after login

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"}"
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template