I noticed that many struggled with encoding and decoding JSON in Go. Here I cover the issues developers run into and how to solve them. Recently, I ha

Go and JSON: Tags, Empty Strings and Nil Values

submited by
Style Pass
2021-09-25 17:00:08

I noticed that many struggled with encoding and decoding JSON in Go. Here I cover the issues developers run into and how to solve them.

Recently, I have been spending a lot of time working with Go. While helping other developers I noticed that many struggled with encoding and decoding JSON. In this guide I cover a lot of the common issues developers run into and how to solve them.

The keys Foo and Bar are use the same format as our struct. You may want these to be lowercase or different from your struct. To do that we can use struct tags like so.

We can exclude the keys by adding a - to our json tag in our struct. Any tags which use a - will be excluded when marshalling a struct. So let’s change on of our tags to - like this:

As you can see Bar is no excluded from the marshalled string. This is useful if you have structs that serve multiple purposes such as database queries and api responses.

In some situations you may send or receive JSON with optional keys which are sometimes present and sometimes not. The issue you may run into is that bools are false, ints are 0 and strings are "" when they are not set. I have some developers make huge workarounds to deal with this issue but there is a simple solution: pointers. Let’s take a look at an example without pointers.

Leave a Comment