Say you are fetching data from a RESTful API using GET requests and want to store the JSON responses. One of the ways to achieve this is by parsing the JSON data into a Go struct. The following example will fetch data related to standings of a football league, UEFA Champions League in this case.
RESTful API used : https://www.football-data.org/
You’ll need a free API key to access the data.
Construct a blueprint of the struct:
Here’s a useful tool that converts JSON to a Go struct type. I have removed a few fields to make the struct simpler. Each field is associated with a JSON tag.
Construct separate struct types for JSON objects that are arrays. In the following example a separate type is constructed for
Standing
andTable
and the fieldsStandings
is a slice ofStanding
i.e.[]Standing
andTables
is a slice ofTable
i.e.[]Table
.
Get JSON data from the API:GetData
function returns a slice of byte. It does the following tasks:
* Makes an HTTP GET request;
* Sets the “X-Auth-Token”
in request header;
* Sets up an HTTP Client that makes an HTTP request and returns an HTTP response, following the auth-token as configured.
* Reads HTTP response body that contains JSON data and converts it to a []byte
.
The []byte
returned can be used to parse JSON encoded data into any struct type using json.Unmarshal
.
Parse JSON into Competitions
struct:GetStandings
function takes the league id
as an argument to build the final url and returns a Competitions
struct that has the parsed JSON data in it.
json.Unamrshal
parses the JSON-encoded data that is in[]byte
and stores the result in the struct whose address is given by&s
.
Note: To make successful GET requests, set the variable apikey.
Voila!
Print the struct on terminal using the format verb %+v
variant that will include the struct’s field names or use package spew
that prints some additional information about the struct.