MarshalJSON() output encrypted json

611 views
Skip to first unread message

Gert

unread,
Dec 27, 2019, 1:55:29 AM12/27/19
to golang-nuts
https://play.golang.org/p/6qKkJhVsnU1

type Payload struct{}

func (p Payload) MarshalJSON() ([]byte, error) {
return []byte("my custom encryption stuf"), nil
}

func main() {
p := Payload{}
j, err := json.Marshal(p)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(j))
}

json: error calling MarshalJSON for type main.Payload: invalid character 'm' looking for beginning of value

How do you skip the check from json.Marshal and just return the []byte directly whatever they are?

Axel Wagner

unread,
Dec 27, 2019, 3:39:51 AM12/27/19
to Gert, golang-nuts
`MarshalJSON` needs to output a valid JSON value, according to the interface. If you don't need the result to be valid JSON, then don't use encoding/json. If you want to use JSON to use it as part of a larger value, you could output a JSON string (but you should familiarize yourself with what a JSON string can and can't contain - e.g. if your encrypted bytes contain quotes, that'll be problematic).

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/554c8ca8-2bca-4321-9ee5-0524e28422a3%40googlegroups.com.

Gert Cuykens

unread,
Dec 27, 2019, 3:52:36 AM12/27/19
to Axel Wagner, golang-nuts
Thanks, Which should I use instead then? The reason I use it is so I
can easily switch between regular json payloads for debugging and
encrypted/signed urlencode payloads

Dan Kortschak

unread,
Dec 27, 2019, 4:22:26 AM12/27/19
to Gert Cuykens, golang-nuts
MarshalText?

Gert Cuykens

unread,
Dec 27, 2019, 4:47:21 AM12/27/19
to Dan Kortschak, golang-nuts
Ok thanks, I will try that but don't think it will be elegant for
turning on and off plain json in a code base, because I have to change
every json.Marshal and json.Umarshal

Dan Kortschak

unread,
Dec 27, 2019, 5:11:30 AM12/27/19
to Gert Cuykens, golang-nuts
It depends what you want to get. json.Marshal picks up
encoding.TextEncoder and Unmarshal, TextDecoder. It will wrap the
marshaled text into a quoted json string and then pull it out again
when you deserialise. From the json.Marshal docs

```
If no MarshalJSON method is present but the value implements
encoding.TextMarshaler instead, Marshal calls its MarshalText method
and encodes the result as a JSON string.
```

Lutz Horn

unread,
Dec 27, 2019, 10:06:05 AM12/27/19
to golang-nuts
The string

"my custom encryption stuff"

is not valid JSON. Why does your type implement MarshalJSON if it does not produce JSON?

Lutz

Von: Gert
Gesendet: ‎27.‎12.‎2019 07:55
An: golang-nuts
Betreff: [go-nuts] MarshalJSON() output encrypted json

--
Reply all
Reply to author
Forward
0 new messages