Home  >  Article  >  Backend Development  >  Why is my json.RawMessage being base64 encoded when using `json.Marshal`?

Why is my json.RawMessage being base64 encoded when using `json.Marshal`?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-09 06:56:02511browse

Why is my json.RawMessage being base64 encoded when using `json.Marshal`?

Base64 Encoding Issue with json.Marshal and json.RawMessage

In the code provided, json.Marshal is applied to a json.RawMessage, which is intended to represent arbitrary JSON data. However, the output is unexpectedly base64 encoded.

Problem

Upon investigation, it becomes evident that json.RawMessage's MarshalJSON method simply returns the byte slice of the message, as seen here:

// MarshalJSON returns *m as the JSON encoding of m.
func (m *RawMessage) MarshalJSON() ([]byte, error) {
    return *m, nil 
}

Therefore, when json.Marshal is called without a pointer to the RawMessage, it mistakenly treats it as an ordinary []byte, resulting in base64 encoding.

Solution

As suggested in the go-nuts thread, the solution lies in providing a pointer to the json.RawMessage when invoking json.Marshal, as shown below:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    raw := json.RawMessage(`{"foo":"bar"}`)
    j, err := json.Marshal(&raw) // Pass pointer to RawMessage
    if err != nil {
        panic(err)
    }
    fmt.Println(string(j))  
}

This approach aligns with the behavior expected from json.Marshal, where it assumes non-pointers to represent raw byte values. By providing a pointer to the RawMessage, it correctly recognizes the message as a JSON value and renders it accordingly.

The above is the detailed content of Why is my json.RawMessage being base64 encoded when using `json.Marshal`?. 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