Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang JSON RawMessage literal

Tags:

json

go

Is it possible to create a json.RawMessage literal in Golang?

I want to be able to do something like this:

type ErrorMessage struct {
    Timestamp string
    Message   json.RawMessage
}

func getTestData() ErrorMessage {
    return ErrorMessage{
        Timestamp: "test-time",
        Message:   "{}"
    }
}

Or something like that. This is the most succinct I've seen. I have not been able to find an example of a "struct" literal for creating raw json messages.

like image 319
eatonphil Avatar asked Dec 25 '22 18:12

eatonphil


1 Answers

The underlying data type for json.RawMessage is a []byte

You can convert your string, or use a byte slice directly in the literal

msg := ErrorMessage{
    Timestamp: "test-time",
    Message:   []byte("{}"),
}

Note that to actually marshal that as expected, you need to use *json.RawMessage, which you can't take the address of in a literal context.

like image 60
JimB Avatar answered Dec 27 '22 10:12

JimB