Go
Beginner
1 min read
Struct Tags and JSON Serialisation
Example
package main
import (
"encoding/json"
"fmt"
"log"
"time"
)
type Address struct {
Street string `json:"street"`
City string `json:"city"`
Zip string `json:"zip,omitempty"`
}
type User struct {
ID int `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
Password string `json:"-"` // never serialised
Address Address `json:"address"`
CreatedAt time.Time `json:"created_at"`
Score *float64 `json:"score,omitempty"`
}
func main() {
u := User{
ID: 1,
Username: "gopher",
Email: "gopher@example.com",
Password: "secret",
Address: Address{Street: "1 Main St", City: "Springfield"},
CreatedAt: time.Now(),
}
// Marshal to JSON
data, err := json.MarshalIndent(u, "", " ")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(data))
// Unmarshal from JSON
raw := `{"id":2,"username":"alice","email":"alice@example.com","address":{"street":"2 Elm St","city":"Shelbyville","zip":"12345"},"created_at":"2024-01-01T00:00:00Z"}`
var u2 User
if err := json.Unmarshal([]byte(raw), &u2); err != nil {
log.Fatal(err)
}
fmt.Printf("Decoded: %+v\n", u2)
}