Skip to content

Golang JSON Marshal With Custom Key (Lowercase, Uppercase …)

If you want to have a custom key (for example uppercased, lowercased, or even a new name) on the JSON marshal output in golang use the `json:”key_name”` tag in front of your field and it will do the magic for you:

Desc  string `json:"book_description"`

And this full example will help you to test it:

package main

import (
	"encoding/json"
	"fmt"
	"log"
)

type Book struct {
	Title string `json:"title"`
	Pages int64  `json:"PAGES"`
	Desc  string `json:"description"`
}

func main() {
	book := Book{
		Title: "Code paste",
		Pages: 101,
		Desc:  "Short and useful snippets",
	}

	jsonBytes, err := json.MarshalIndent(book, "", " ")
	if err != nil {
		log.Fatalf("failed to marshal: %s", err)
	}

	fmt.Println(string(jsonBytes))
}
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *