Using Go’s json.RawMessage

Noam Tenne
2 min readFeb 15, 2019

tl;dr

json.RawMessage is a byte array that can be plugged into any model that’s being marshaled or unmarshaled.

What’s a “raw message”?

We can think of the raw message as a piece of information that we decide to ignore at the moment. The information is still there but we choose to keep it in its raw form — a byte array.

The reason for it being a byte array is that short of machine code, the byte array is the purest form of data. Every piece of information can be viewed as an array of bytes. In the same manner, every JSON message is eventually serialized to an array of bytes. So if we can regard the whole JSON message as a byte array, we should be able to regard bits of JSON as a byte array.

That’s were json.RawMessage comes in.

If we look into the source of Go, and into the type of json.RawMessage, it’s literally a type alias for []byte:

Excerpt from Go source

So a raw message can represent a complete JSON document, but it can also represent any value or sub document of a JSON document.

When should I use json.RawMessage?

When you don’t know or when you don’t care.

Most JSON examples out there will demonstrate how to fully resolve the whole JSON document into a Go structure. Whether it’s a map, or a structure you’ve composed:

But if you don’t know or just don’t care what part of the document should look like, you don’t have to define it. Just use json.RawMessage as a place holder:

--

--