31

I run the following code:

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))  
}

Playground: http://play.golang.org/p/qbkEIZRTPQ

Output:

"eyJmb28iOiJiYXIifQ=="

Desired output:

{"foo":"bar"}

Why does it base64 encode my RawMessage as if it was an ordinary []byte?

After all, RawMessage's implementation of MarshalJSON is just returning the byte slice

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

1 Answer 1

75

Found the answer in a go-nuts thread

The value passed to json.Marshal must be a pointer for json.RawMessage to work properly:

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))  
}
Sign up to request clarification or add additional context in comments.

2 Comments

How can I use its key and value from j variable?
@RockBalbao j is the JSON encoded string. To access the values, you need to use json.Unmarshal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.