Go📦Standard Libraryintermediate
encoding/json — JSON Marshal/Unmarshal
Go · Standard Library · Run with go run
Explanation
`encoding/json` serializes Go values to JSON (`json.Marshal`) and deserializes JSON to Go values (`json.Unmarshal`). Struct fields are controlled with `json:` struct tags: `json:"name"` sets the key name, `json:"name,omitempty"` omits zero values, `json:"-"` excludes a field. `json.NewEncoder`/`json.NewDecoder` stream JSON to/from an `io.Writer`/`io.Reader`.
Real-World Scenario
An API handler decodes a JSON request body into a struct, validates it, and encodes a response: `json.NewDecoder(r.Body).Decode(&req)` / `json.NewEncoder(w).Encode(resp)` — no buffering the whole body into memory.
Quick Snippet
snippet.go
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
Email string `json:"email,omitempty"` // omit if empty
Password string `json:"-"` // never marshal
}
p := Person{Name: "Alice", Age: 30}
data, err := json.Marshal(p)
// {"name":"Alice","age":30}
var p2 Person
err = json.Unmarshal(data, &p2)
// Streaming decode from HTTP body
var req Request
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "bad JSON", 400)
return
}Full Example
json_encode.go
// Compile: go run json_encode.go
// Output:
// encoded: {"name":"Alice","age":30}
// decoded: Alice (30)
// with omitempty: {"name":"Bob","age":0}
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
Email string `json:"email,omitempty"`
Password string `json:"-"`
}
func main() {
p := Person{Name: "Alice", Age: 30, Password: "secret"}
data, err := json.Marshal(p)
if err != nil {
panic(err)
}
fmt.Println("encoded:", string(data))
var p2 Person
if err := json.Unmarshal(data, &p2); err != nil {
panic(err)
}
fmt.Printf("decoded: %s (%d)\n", p2.Name, p2.Age)
fmt.Println("password hidden:", p2.Password == "")
// omitempty: Age is zero, Email is empty — only name included
p3 := Person{Name: "Bob"}
data3, _ := json.Marshal(p3)
fmt.Println("with omitempty:", string(data3))
}
Run command
go run json_encode.go