Working with Slice in Go `json`

Overview

Suppose we have the following struct:

type Blogpost struct {
    Title string 
    Tags  []string
}

We want to encode it into JSON and make an API call with this payload. If we encode (marshall) a Go struct with Slice in its fields, we can make four possible results:

  1. Tags with value(s)
  2. Empty tags
  3. Null tags
  4. Omitted tags

1. Tags with value(s)

package main

import (
    "encoding/json"
    "fmt"
)

type Blogpost struct {
    Title string   `json:"title"`
    Tags  []string `json:"tags"`
}

func main() {
    blogpost := Blogpost{
        Title: "Blog Title",
        Tags:  []string{"first", "second"},
    }
    var jsonData []byte
    jsonData, _ = json.Marshal(blogpost)
    fmt.Println(string(jsonData))
}

Result:

{
  "title": "Blog Title",
  "tags": ["first","second"]
}

2. Empty array

package main

import (
    "encoding/json"
    "fmt"
)

type Blogpost struct {
    Title string   `json:"title"`
    Tags  []string `json:"tags"`
}

func main() {
    blogpost := Blogpost{
        Title: "Blog Title",
        Tags:  []string{},
    }
    var jsonData []byte
    jsonData, _ = json.Marshal(blogpost)
    fmt.Println(string(jsonData))
}

Result:

{
  "title": "Blog Title",
  "tags": []
}

3. Null tags

package main

import (
    "encoding/json"
    "fmt"
)

type Blogpost struct {
    Title string   `json:"title"`
    Tags  []string `json:"tags"`
}

func main() {
    blogpost := Blogpost{
        Title: "Blog Title",
    }
    var jsonData []byte
    jsonData, _ = json.Marshal(blogpost)
    fmt.Println(string(jsonData))
}

Result:

{
  "title": "Blog Title",
  "tags": null
}

4. Omitted tags

package main

import (
    "encoding/json"
    "fmt"
)

type Blogpost struct {
    Title string   `json:"title"`
    Tags  []string `json:"tags,omitempty"`
}

func main() {
    blogpost := Blogpost{
        Title: "Blog Title",
    }
    var jsonData []byte
    jsonData, _ = json.Marshal(blogpost)
    fmt.Println(string(jsonData))
}

Result:

{
  "title": "Blog Title"
}

The field will be omitted since the empty value of Slice is nil.