JSON handling in Go
Go has built-in support for encoding and decoding JSON data.
The encoding/json package provides functions for encoding Go values into JSON and decoding JSON into Go values.
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
p := Person{Name: "John Doe", Age: 42}
data, err := json.Marshal(p)
if err != nil {
// handle the error
}
fmt.Println(string(data)) // prints {"name":"John Doe","age":42}
var q Person
err = json.Unmarshal(data, &q)
if err != nil {
// handle the error
}
fmt.Println(q.Name, q.Age) // prints John Doe 42
In this example, we define a Person struct with two fields: Name and Age. We then create a new Person value and encode it into JSON by using the json.Marshal() function.
We also decode the JSON data back into a Person value by using the json.Unmarshal() function.
No comments:
Post a Comment