Golang Custom JSON Marshal Example

In this article we are going to see how to perform custom JSON Marshalling in Go (Golang). Golang has a powerful builting json encoding package that can be used right from the standard library without using any third party dependencies. The standard JSON functionality can be seen in this article here where we discuss how to marshall and unmarshal a struct in Go.

Let's first see an example and then we will create custom code to marshal and unmarshal our structs.

Simple JSON Marshal

package main

import (
    "fmt"
    "encoding/json"
)

type User struct {
    Name string
    Age int
    Active bool
    lastLoginAt string
}

func main() {
        u, err := json.Marshal(User{Name: "Bob", Age: 10, Active: true, lastLoginAt: "today"})
        if err != nil {
            panic(err)
        }
        fmt.Println(string(u)) // {"Name":"Bob","Age":10,"Active":true}
}

Custom JSON Marshal In Go (Golang)

In this example we update our prior code to use a custom JSON Marshaller. First let's have a look at the Marshaler interface

type Marshaler interface {
  MarshalJSON() ([]byte, error)
}

Marshaler is the interface implemented by types that can marshal themselves into valid JSON.

If we want to create a custom json marshaller in Go (Golang) we just need to implement and override this interface for the struct that we want to marshal. Let's see a concrete example

package main

import (
	"encoding/json"
	"fmt"
)

type User struct {
	Name        string
	Age         int
	Active      bool
	lastLoginAt string
}

func (u User) MarshalJSON() ([]byte, error) {
	activeStr := "I am not active"
	if u.Active {
		activeStr = "I am active"
	}
	return json.Marshal(struct {
		NameAndAge string
		Active     string
	}{
		NameAndAge: fmt.Sprintf("My name is %s and I am %d years old", u.Name, u.Age),
		Active:     activeStr,
	})
}

func main() {
	u, err := json.Marshal(User{Name: "Bob", Age: 10, Active: true, lastLoginAt: "today"})
	if err != nil {
		panic(err)
	}
	fmt.Println(string(u)) // {"NameAndAge":"My name is Bob and I am 10 years old","Active":"I am active"}
}

You can run it yourself on the Golang Playground https://go.dev/play/p/L9BUmoQEuDK

Join the Golang Developers Community on Golang Cafe