| by Arround The Web | No comments

Go JSON Omitempty Usage (JSON Omitempty)

JSON is probably one of the most popular data interchange formats of the modern age. It is very simplistic yet powerful and versatile to power the massive applications and API endpoints.

It is therefore no doubt that working with JSON in languages such as Go is very common. However, often times, when serializing structs into JSON objects and vice versal, we need to control the fields that we want to include in the output.

This is where the “omitempty” attribute or tag comes into play. It allows us to tell the compiler not to include any field that is empty or have a zero value.

In this tutorial, we will explore the workings of this tag and how it can help us in serializing and deserializing the JSON data in the Go language.

What Is Omitempty?

The omitempty is a struct field tag that we can use in combination with the encoding/JSON package to control the serialization of Go struct fields into JSON objects.

When the JSON encoder encounters the “omitempty” field tag on a struct, it omits the field from the JSON output if it contains an empty value or a zero.

This is especially useful when we want to create more concise JSON representations or filter out the unnecessary data.

Use the Omitempty Tag in Golang

Let us explore how to use the “omitempty” tag in a Go struct.

We can start by defining a struct and add the tag as shown in the following syntax:

Field  type 'json:"field,omitempty"'

For example:

type Car struct {
    Model   string 'json:"model"'
    Year    int    'json:"year,omitempty"'
    Mileage int    'json:"mileage,omitempty"'
}

In this case, we define a struct called “Car” with three main fields. The “Year” and “Mileage” contains the “omitempty” tag which allows the encoder to discard them as valid JSON in the output if they contain 0 or an empty string.

Encode a Struct to JSON

To encode an instance of the struct to JSON with omitempty handling, we can use the “json.Marshal” function from the encoding/JSON package.

package main
import (
    "encoding/json"
    "fmt"
)

type Car struct {
    Model   string 'json:"model"'
    Year    int    'json:"year,omitempty"'
    Mileage int    'json:"mileage,omitempty"'
}
func main() {
    car := Car{
        Model:   "Audi",
        Year:    0,
        Mileage: 200,
    }
    jsonData, err := json.Marshal(car)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Println(string(jsonData))

}

In this case, since the “Year” field has a value of 0, it is omitted from the JSON output as shown in the following example:

{"model":"Audi","mileage":200

Decode a JSON Data to a Struct

To decode a JSON data into a Go struct with omitempty handling, we can use the “json.Unmarshal” function from the encoding/JSON package.

An example is as follows:

package main
import (
    "encoding/json"
    "fmt"
)
type Car struct {
    Model   string 'json:"model"'
    Year    int    'json:"year,omitempty"'
    Mileage int    'json:"mileage,omitempty"'
}
func main() {
    jsonStr := '{"model":"Audi","year":0,"mileage":200}'
    var car Car
    err := json.Unmarshal([]byte(jsonStr), &car)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Printf("Model: %s, Year: %d, Mileage: %d\n", car.Model, car.Year, car.Mileage)
}

In this example, if the JSON data does not contain a “year” field, the “Year” field in the “car” struct will be set to an empty string. This allows us to handle the optional fields gracefully.

Omit Empty Slices and Maps

We can also apply the empty or zero value filtering in a slice or map of a given struct as demonstrated in the following example:

package main

import (
    "encoding/json"
    "fmt"
)

type Car struct {
    Model      string            'json:"model"'
    Color      string            'json:"color"'
    Features   []string          'json:"features,omitempty"'
    Attributes map[string]string 'json:"attributes,omitempty"'
}

func main() {
    car := Car{
        Model:      "Toyota Camry",
        Color:      "Silver",
        Features:   []string{"GPS", "Leather Seats"},
        Attributes: make(map[string]string),
    }

    jsonData, _ := json.Marshal(car)
    fmt.Println(string(jsonData))
}

The resulting string is as follows:

{"model":"Toyota Camry","color":"Silver","features":["GPS","Leather Seats"]}

You will notice that the “omitempty” tag applies the attributes map which contains the empty values and hence not included in the resulting JSON string.

Conclusion

In this tutorial, we learned everything about the “omitempty” tag in Go structs to allow us to exclude any field that contains an empty string on zero value in the resulting JSON string and vice versa.

Share Button

Source: linuxhint.com

Leave a Reply