Converting to and from JSON
In this section, we will look at getting and sending data from and to JSON. We will also look at creating a structure to handle data and how the JSON conversion is done.
When dealing with JSON in Golang via the standard library, we’ve got two primary options –json.Marshal/Unmarshal
and json.NewEncoder(io.Writer)/NewDecoder(io.Reader)
. In this chapter, we will look at using the Encoder
/Decoder
methods. The reason for using these methods is that we can chain a function to the encoder/decoder that’s returned and call the .Encode
and .Decode
functions with ease. Another benefit of this approach is that it uses the streaming interface (namely io.Reader
and io.Writer
, used to represent an entity from/to which you can read or write a stream of bytes – the Reader
and Writer
interfaces are accepted as input and output by many utilities and functions in the standard library), so we have other choices than Marshal
, which works with preallocated...