[file:///Users/mrj/Downloads/lets-go-further/html/04.01-json-decoding.html](file:///Users/mrj/Downloads/lets-go-further/html/04.01-json-decoding.html)
Just like JSON encoding, there are two approaches that you can take to decode JSON into a native Go object: using a json.Decoder
type or using the json.Unmarshal()
function.
Both approaches have their pros and cons, but for the purpose of decoding JSON from a HTTP request body, using json.Decoder
is generally the best choice. It’s more efficient than json.Unmarshal()
, requires less code, and offers some helpful settings that you can use to tweak its behavior.
There are few important and interesting things about this code to point out:
Decode()
you must pass a non-nil pointer as the target decode destination. If you don’t use a pointer, it will return a json.InvalidUnmarshalError
error at runtime.encoding/json
package.r.Body
after it has been read. This will be done automatically by Go’s http.Server
, so you don’t have too.It’s important to mention that certain JSON types can be only be successfully decoded to certain Go types. For example, if you have the JSON string "foo"
it can be decoded into a Go string
, but trying to decode it into a Go int
or bool
will result in an error at runtime (as we’ll demonstrate in the next chapter).
The following table shows the supported target decode destinations for the different JSON types: