Lesson 36 of 60 · Go
Encoding & Decoding – JSON, XML, and Gob
Duration: 20 minutes
JSON (most common)
This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
p := Person{"Bob", 42}
bytes, _ := json.Marshal(p)
fmt.Println(string(bytes)) // {"name":"Bob","age":42}
XML
type Item struct {
XMLName xml.Name `xml:"item"`
ID int `xml:"id,attr"`
Title string `xml:"title"`
}
Gob (binary Go encoder)
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
enc.Encode(p) // p must be exported fields