Skip to content

JSON

In Go, the encoding/json package provides robust support for encoding (marshaling) and decoding (unmarshaling) JSON data.

package main
import (
"encoding/json"
"fmt"
"log"
)
type Person struct {
Name string `json:"name"` // JSON field name
Age int `json:"age"`
Email string `json:"email,omitempty"` // Omit if empty
}
func main() {
person := Person{Name: "Alice", Age: 30, Email: ""}
jsonData, err := json.Marshal(person)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(jsonData)) // Output: {"name":"Alice","age":30}
}