Home > Backend Development > Golang > Why Does json.Marshal Encode json.RawMessage as Base64?

Why Does json.Marshal Encode json.RawMessage as Base64?

DDD
Release: 2024-11-08 21:40:02
Original
946 people have browsed it

Why Does json.Marshal Encode json.RawMessage as Base64?

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

Output:

{"foo":"bar"}
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template