Golang-How to parse JSON data into a nested struct

Penthaa
2 min readMay 22, 2019

--

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 and Table and the fields Standings is a slice of Standing i.e. []Standing and Tables is a slice of Table 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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Penthaa
Penthaa

Written by Penthaa

Infosec | Gopher | CSE Grad from IIIT-Bh | Find me on — GitHub - github.com/penthaapatel | Website — penthaapatel.github.io

Responses (1)

Write a response