Home  >  Article  >  Backend Development  >  Why does marshalling a json.RawMessage value result in a base64-encoded string instead of raw JSON?

Why does marshalling a json.RawMessage value result in a base64-encoded string instead of raw JSON?

DDD
DDDOriginal
2024-11-12 04:54:01749browse

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!

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