Skip to content

Golang: Removing or Hiding Fields in JSON Marshal

If you want to remove a field from a struct just put `json:”-“` in front of the fields you want to hide:

type User struct {
	Name     string
	Url      string
	Password string `json:"-"`
}

Take a look at this example which prevent the password field from being exported in the final JSON string.

package main

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

type User struct {
	Name     string
	Url      string
	Password string `json:"-"`
}

func main() {

	user := User{
		Name:     "Morteza",
		Url:      "https://www.code-paste.com/",
		Password: "MySeCreTpasS!",
	}

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

	fmt.Println(string(b))
}

Leave a Reply

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