Encoding JSON
We have studied how to unmarshal JSON into a struct. We will now do the opposite: marshal a struct into JSON. When we talk about encoding JSON, what we mean is we are taking a Go struct and converting it to a JSON data structure. The typical scenario in which this is done is when you have a service that is responding to an HTTP request from a client. The client wants the data in a certain format, and this is frequently JSON. Another situation is that the data is stored in a NoSQL database and it requires JSON as the format, or even a traditional database that has a column with a data type of JSON.
We need to be able to Marshal
the Go struct into a JSON-encoded structure. To be able to do this, we will need to import the encoding/json
package. We will be using the json.Marshal
function:
func Marshal(v interface{}) ([]byte, error)
The v
becomes encoded as JSON. Typically, v
is a struct
. The Marshal()
function returns the JSON encoding as a slice of bytes and an...