Encoding and Decoding JSON
The encoding/json
package in Go provides two main functions for working with JSON data: json.Marshal()
and json.Unmarshal()
.
json.Marshal()
is used to encode Go data structures (such as structs, slices, and maps) to JSON. This function takes a Go data structure as input and returns a byte slice representing the JSON data. Here's an example:
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
person := Person{
Name: "John Doe",
Age: 30,
}
jsonData, err := json.Marshal(person)
if err != nil {
fmt.Println("Error encoding JSON:", err)
return
}
fmt.Println("JSON data:", string(jsonData))
json.Unmarshal()
is used to decode JSON data to Go data structures. This function takes a byte slice of JSON data and a pointer to a Go data structure as input, and it populates the data structure with the decoded values. Here's an example:
var decodedPerson Person
err = json.Unmarshal(jsonData, &decodedPerson)
if err != nil {
fmt.Println("Error decoding JSON:", err)
return
}
fmt.Println("Decoded person:", decodedPerson)
It's important to note that the JSON field names must match the struct field names (or the json
tag values) for the decoding to work correctly. If the field names don't match, the json.Unmarshal()
function will not be able to populate the corresponding fields in the Go data structure.
Both json.Marshal()
and json.Unmarshal()
can handle a wide range of Go data types, including structs, slices, maps, and primitive types. However, if the input data is not compatible with the target data structure, the functions will return an error.
To handle errors during JSON encoding and decoding, you should always check the error return value and handle it appropriately in your code.