This blog post is brought to you by the developer of BitBudget. BitBudget is an automated budgeting app for Android and iOS which syncs with your bank account and helps you avoid overspending. If you’d like to quit living paycheck-to-paycheck and get a better handle on your finances, download it today! https://bitbudget.io
Welcome back internet friend,
At the moment I’m currently doing a little hacking in Golang, and just wanted to post this quick little example of how to work with an api and parse json data in Go. Unlike some of the other languages I’ve worked with, in Golang you will need to create a struct to represent the JSON data you are receiving from the API endpoint you are hitting. That’s the trickiest part in my opinion. Also, the JSON data you will be working with is going to be an array of bytes, not a string. Last, you’ll use json.Unmarshal to parse your JSON and extract the information you are looking for.
Unfortunately, I don’t have time to write up a detailed post about how all of this works. However, I think the code snippet below is pretty cool and should provide a good reference if you happen to be playing around with APIs and JSON using Go. Note, the code below is using RapidAPI’s Hacker News endpoint to provide the JSON data. So if you’d like to try running this code yourself, make sure to visit rapidapi.com, register for an account, and replace the API key below with your own. Enjoy!
UPDATE (1/27/2020): Remember to use a JSON to Golang Struct Conversion Tool such as JSON-to-Go to easily map Golang Structs to the JSON objects you want to decode. The code snippet below provides a good example of a struct created with JSON-to-Go: