Explain the use of Go's JSON encoding and decoding for data serialization?
In Go, the encoding/json package provides support for encoding Go data structures into JSON format and decoding JSON data into Go data structures. JSON is a widely used format for data serialization and exchange, and is supported by many programming languages and web APIs.
Here is an example of encoding a Go data structure into JSON:
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
p := Person{Name: "John Doe", Age: 42}
b, err := json.Marshal(p)
if err != nil {
fmt.Println("Error:", err)
}
fmt.Println(string(b)) // prints {"name":"John Doe","age":42}
}
In this example, we define a Go data structure called **Person**
with two fields: **Name**
and **Age**
. We use struct tags to specify the corresponding JSON field names for each field. Then we create an instance of the **Person**
struct, and use the **json.Marshal()**
function to encode it into a JSON byte slice.
Here is an example of decoding a JSON byte slice into a Go data structure:
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
b := []byte(`{"name":"John Doe","age":42}`)
var p Person
err := json.Unmarshal(b, &p)
if err != nil {
fmt.Println("Error:", err)
}
fmt.Printf("%#v\n", p) // prints main.Person{Name:"John Doe", Age:42}
}
In this example, we define the same **Person**
struct as before, and create a JSON byte slice representing a **Person**
object. Then we use the **json.Unmarshal()**
function to decode the JSON byte slice into a **Person**
struct.
The **encoding/json**
package supports many other features for customizing JSON encoding and decoding, such as handling embedded structs, ignoring empty fields, and customizing field names and types.