Home > Backend Development > Golang > 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
Release: 2024-11-12 04:54:01
Original
800 people have browsed it

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

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

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!

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