Member-only story
Working With JSON in Golang
Handling JSON data with Go

Enabling developers to easily and effectively build highly performant, scalable web services is one of Golang’s best selling points.
As we know, JSON is the industry standard for data serialization when communicating with a user-facing web service. Luckily, Go enables you to work with JSON in a very straightforward and productive way. In this article I will:
- Demonstrate how to work with the JSON module that is built into the Go standard library
- Show how to convert JSON data to Go objects and vice versa
- Talk about some neat tools that can speed up the process of working with JSON
Go has a very powerful standard library. For working with JSON data, we do not need to fetch any third-party libraries, as the built-in one has all we need.
Let’s look at a code snippet that does some basic manipulation with JSON:
This is a very basic example, in which we take a slice of Go structs (books in this case) and serialize it to a JSON format so that we can send it over the wire to a client requesting this data.
One of the first things you may have noticed is the way we define the fields of the Book struct. Each attribute of our struct defines the way it will be displayed when serialized to JSON in the backticks (json:”title”)
.
This is a very useful feature of Go, which you can easily test by changing for example title
to book_title
. This can be very useful when the need for changing the format of your JSON response in REST API occurs.
Now let’s look at the way we actually converted the data- the Marshal method takes in an empty interface (meaning you can pass literally any Go data structure you like), and attempts to serialize the data. If it cannot, you will get an error. This is why it is very important to check for errors. If the serialization went successfully, it will return a slice of bytes ready to be transferred through the…