Golang productivity hacks part 1: auto-generating data structures

Jcdan
Towards Dev
Published in
2 min readJan 26, 2022

--

Intro

Sometimes when writing software, having the proper tools and practices can make a big difference in the actual amount of work you get done.

This post will be the first of a series about golang tips and hacks for greater productivity.

Generating data structures from JSON

My first tip is simple yet very efficient, is to automatically convert a JSON string or file to a struct.

This is very useful when for instance making an HTTP call to an API.

Here is a quick example in which we make an HTTP request to get the public holidays for this year. The API is public and the code should work fine without a Token:

The API returns a JSON object that we print. From the code, we get this output:

The fields of a structure that could represent this JSON can add up quickly.

Don't try to manually create the structure. Work smart.

Automatically generating the Go structure

To generate the structure, we could be using my favorite IDE: Goland. In Goland, simply paste a JSON structure and it will prompt you to translate the JSON to a struct.

But for this blog post, we will be working with a free tool JSON-to-go.

Simply input the JSON and it will output this structure automatically:

That's it for this one! Stay tuned for the new post of my productivity series.

--

--

Experience software developer in a quest to democratize software development. More here: https://www.linkedin.com/in/jcdansereau