JSON Encoding and Decoding
Use encoding/json
to convert Go structs to and from JSON.
- Encoding:
json.Marshal(data)
- Decoding:
json.Unmarshal(jsonData, &targetStruct)
Add struct tags like `json:"field_name"`
to map JSON keys to Go fields.
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
data := Person{"Alice", 30}
jsonBytes, _ := json.Marshal(data)