How do I encode a struct to/from JSON in Go?

Encoding and decoding JSON in Go is achieved using the `encoding/json` package. Below is an example of how to encode a struct to JSON and decode JSON back into a struct.

Keywords: Go, JSON, Struct, Encoding, Decoding, `encoding/json`
Description: This example demonstrates how to work with JSON in Go by encoding a struct to JSON format and decoding it back to the original struct.
package main import ( "encoding/json" "fmt" ) type Person struct { Name string `json:"name"` Age int `json:"age"` } func main() { // Create an instance of Person person := Person{Name: "John Doe", Age: 30} // Encode struct to JSON jsonData, err := json.Marshal(person) if err != nil { fmt.Println("Error encoding JSON:", err) return } fmt.Println("Encoded JSON:", string(jsonData)) // Decode JSON back to struct var decodedPerson Person err = json.Unmarshal(jsonData, &decodedPerson) if err != nil { fmt.Println("Error decoding JSON:", err) return } fmt.Println("Decoded Struct:", decodedPerson) }

Keywords: Go JSON Struct Encoding Decoding `encoding/json`