Introduction to Go encoding/json
Golang provides high-performance JSON processing via the standard library encoding/json package.
1. Struct Tags and Unmarshaling
Define Go structs with json: tag annotations to map JSON keys:
package main
import (
"encoding/json"
"fmt"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email,omitempty"`
}
func main() {
jsonData := []byte(`{"id": 1, "name": "Go Developer"}`)
var u User
json.Unmarshal(jsonData, &u)
fmt.Println(u.Name)
}
2. Marshaling Structs to Formatted JSON
u := User{ID: 2, Name: "Alice"}
output, _ := json.MarshalIndent(u, "", " ")
fmt.Println(string(output))
Format and inspect Golang JSON outputs in your browser using JSON Workshop.