JSON in Go with encoding/json
Go ships with the encoding/json package in the standard library. No external dependency is required.
Struct Field Tags
Use json:"key_name" struct tags to control JSON key names. Use json:"field,omitempty" to omit zero-value fields.
Working with Unknown JSON
Use map[string]interface{} or json.RawMessage for dynamic or partially-known JSON structures.
package main
import (
"encoding/json"
"fmt"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
IsActive bool `json:"is_active"`
Roles []string `json:"roles,omitempty"`
}
func main() {
// Parse JSON string
jsonStr := `{"id":1,"name":"Alice","is_active":true,"roles":["admin"]}`
var user User
if err := json.Unmarshal([]byte(jsonStr), &user); err != nil {
panic(err)
}
fmt.Println(user.Name) // Alice
// Serialize to JSON
jsonBytes, _ := json.Marshal(user)
// Pretty print
pretty, _ := json.MarshalIndent(user, "", " ")
fmt.Println(string(pretty))
}