Sending JSON Responses
In this section of the book, we’re going to update our API handlers so that they return JSON responses instead of just plain text.
JSON (which is an acronym for JavaScript Object Notation) is a human-readable text format which can be used to represent structured data. As an example, in our project a movie could be represented with the following JSON:
To give you a very quick overview of the JSON syntax…
- The parentheses
{}
define a JSON object, which is made up of comma-separated key/value pairs. - The keys must be strings, and the values can be either strings, numbers, booleans, other JSON objects, or an array of any of those things (enclosed by
[]
). - Strings must be surrounded by double-quotes
"
(rather than single quotes'
) and boolean values are eithertrue
orfalse
. - Outside of a string, whitespace characters in JSON do not carry any significance — it would be perfectly valid for us to represent the same movie using the following JSON instead:
If you’ve not used JSON at all before, then this beginner’s guide provides a comprehensive introduction and I recommend reading it before following on.
In this section of the book you’ll learn:
How to send JSON responses from your REST API (including error responses).
How to encode native Go objects into JSON using the
encoding/json
package.Different techniques for customizing how Go objects are encoded to JSON — first by using struct tags, and then by leveraging the
json.Marshaler
interface.How to create a reusable helper for sending JSON responses, which will ensure that all your API responses have a sensible and consistent structure.