How to Marshal/Unmarshal Enums in JSON in Go

Go enums marshal to JSON as their underlying integer or string values automatically without custom code.

Go enums (defined as type aliases for int or string) marshal and unmarshal as their underlying type by default, so no special code is required. Use encoding/json directly on the enum value or a struct containing it.

package main

import (
	"encoding/json"
	"fmt"
)

type Status int

const (
	StatusPending Status = iota
	StatusActive
	StatusClosed
)

type Task struct {
	Name   string
	Status Status
}

func main() {
	task := Task{Name: "Deploy", Status: StatusActive}
	b, _ := json.Marshal(task)
	fmt.Println(string(b)) // {"Name":"Deploy","Status":1}

	var t Task
	json.Unmarshal(b, &t)
	fmt.Println(t.Status) // 1
}

If you need string values (e.g., "active") instead of numbers, implement MarshalJSON and UnmarshalJSON on the enum type to convert between the string and the underlying integer.